Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rollback selected SelectedValue of the combo box using WPF MVVM

Tags:

mvvm

wpf

I have something like it will pop to the user for getting confirmation of changes. If he clicks no I am setting the selectedValue in view model to the previous selection. But its not getting displayed correctly in view. Please help.

like image 823
gowri Avatar asked May 04 '11 07:05

gowri


3 Answers

Very simple solution for .NET 4.5.1+:

<ComboBox SelectedItem="{Binding SelectedItem, Delay=10}" ItemsSource="{Binding Items}"  />

It's works for me in all cases. Just fire NotifyPropertyChanged without value assignment to rollback.

like image 51
Dvor_nik Avatar answered Nov 15 '22 07:11

Dvor_nik


If the user clicks no and you try to revert the value and then call OnPropertyChanged, WPF will swallow the event since it is already responding to that event. One way to get around this is to use the dispatcher and call the event outside of the current event context.

System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { OnPropertyChanged("ComSelectedValue"); }), null);
like image 39
shaun Avatar answered Nov 15 '22 08:11

shaun


WPF seems to validate that the bound property has changed before updating the UI. So simply invoking an NotifyPropertyChanged()/OnPropertyChanged() doesn't do the trick.

The problem is that since the property hasn't changed, WPF doesn't think it needs to refresh the combo box.

here is the incredibly hackish way I handle it in my ViewModels;

private int _someProperty = -1;
public int SomeProperty
{
    if (_someProperty != -1 && doYesNo() == Yes)
    {
       _someProperty = value;
    }
    else if (_someProperty != -1)
    {
       int oldValue = _someProperty;
       _someProperty = -1; // Set to a different/invalid value so WPF sees a change
       Dispatcher.BeginInvoke(new Action(() => { SomeProperty = oldValue; }));
    }
    else 
    {
       _someProperty = value;
    }
    NotifyPropertyChanged("SomeProperty");
}

Not pretty but it works reliably.

like image 33
NebulaSleuth Avatar answered Nov 15 '22 08:11

NebulaSleuth