Home > Net >  SelectionChanged alternative in Avalonia
SelectionChanged alternative in Avalonia

Time:12-10

SelectionChanged in Avalonia is unfortunately broken, and hasn't been fixed for years. For example:

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {             
            var vm = (MainWindowViewModel)DataContext;              
            Debug.WriteLine($"{vm.SelectedValue}");
        }

This will print value that was selected previously, not at this moment, because OnSelectionChanged fires before selection was changed, not during, not after. This essentially means that it serves no purpose, because if you want state of your application to change when certain value got changed you can't do that, because it doesn't know about current value.

Is it possible to somehow override it or implement your own solution that actually works?

CodePudding user response:

As mentioned in the comments, it would be better to handle the logic in the view model, not in the code-behind. But answering the question about how to implement it in an alternative way, you could create and raise an event in your view model instead:

// ViewModel

public delegate void SelectedValueChangedEvent();
public SelectedValueChangedEvent? SelectedValueChanged;

// ...
// call it when the "SelectedValue" has already changed
SelectedValueChanged?.Invoke();
// if using reactiveui you can do it this way:
// this.WhenAnyValue(x => x.SelectedValue).Subscribe(x => SelectedValueChanged?.Invoke());

Then in the view you have to subscribe to this event, but only when the DataContext is already set:

// View

public MainWindow()
{
    // ...
    PropertyChanged  = (s, e) =>
    {
        if (e.Property.Name == "DataContext" && DataContext is MainWindowViewModel vm)
        {
            vm.SelectedValueChanged  = () => Debug.WriteLine(vm.SelectedValue);
        }
    }; 
}

You can also put parameters to the SelectedValueChangedEvent delegate if you wish.

  • Related