Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel combobox selection in WPF with MVVM

I've got a combobox in my WPF application:

<ComboBox  ItemsSource="{Binding CompetitorBrands}" DisplayMemberPath="Value"     SelectedValuePath="Key" SelectedValue="{Binding Path=CompMfgBrandID, Mode=TwoWay,    UpdateSourceTrigger=PropertyChanged}" Text="{Binding CompMFGText}"/> 

Bound to a collection of KeyValuePair<string, string>

Here is the CompMfgBrandID property in my ViewModel:

public string CompMfgBrandID {     get { return _compMFG; }     set     {             if (StockToExchange != null && StockToExchange.Where(x => !string.IsNullOrEmpty(x.EnteredPartNumber)).Count() > 0)         {             var dr = MessageBox.Show("Changing the competitor manufacturer will remove all entered parts from the transaction.  Proceed?",                 "Transaction Type", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);             if (dr != DialogResult.Yes)                 return;         }          _compMFG = value;         StockToExchange.Clear();          ...a bunch of other functions that don't get called when you click 'No'...         OnPropertyChanged("CompMfgBrandID");     } } 

If you choose "yes", it behaves as expected. Items are cleared and the remaining functions are called. If I choose 'No', it returns and doesn't clear my list or call any of the other functions, which is good, but the combobox still displays the new selection. I need it to revert back to the original selection, as if nothing had changed, when the user picks 'No'. How can I accomplish this? I also tried adding e.Handled = true in codebehind, to no avail.

like image 291
drowned Avatar asked Oct 17 '11 21:10

drowned


1 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. You can rollback selection in combobox, just fire NotifyPropertyChanged without value assignment.

like image 98
Dvor_nik Avatar answered Sep 28 '22 08:09

Dvor_nik