Cancel combobox selection in WPF with MVVM

后端 未结 12 1490
你的背包
你的背包 2020-12-08 10:23

I\'ve got a combobox in my WPF application:



        
12条回答
  •  清歌不尽
    2020-12-08 11:04

    Here is the general flow that I use (doesn't need any behaviors or XAML modifications):

    1. I just let the change pass through the ViewModel and keep track of whatever's passed in before. (If your business logic requires the selected item to not be in an invalid state, I suggest moving that to the Model side). This approach is also friendly to ListBoxes that are rendered using Radio Buttons as making the SelectedItem setter exit as soon as possible will not prevent radio buttons from being highlighted when a message box pops out.
    2. I immediately call the OnPropertyChanged event regardless of the value passed in.
    3. I put any undo logic in a handler and call that using SynchronizationContext.Post() (BTW: SynchronizationContext.Post also works for Windows Store Apps. So if you have shared ViewModel code, this approach would still work).

      public class ViewModel : INotifyPropertyChanged
      {
          public event PropertyChangedEventHandler PropertyChanged;
      
          public List Items { get; set; }
      
          private string _selectedItem;
          private string _previouslySelectedItem;
          public string SelectedItem
          {
              get
              {
                  return _selectedItem;
              }
              set
              {
                  _previouslySelectedItem = _selectedItem;
                  _selectedItem = value;
                  if (PropertyChanged != null)
                  {
                      PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
                  }
                  SynchronizationContext.Current.Post(selectionChanged, null);
              }
          }
      
          private void selectionChanged(object state)
          {
              if (SelectedItem != Items[0])
              {
                  MessageBox.Show("Cannot select that");
                  SelectedItem = Items[0];
              }
          }
      
          public ViewModel()
          {
              Items = new List();
              for (int i = 0; i < 10; ++i)
              {
                  Items.Add(string.Format("Item {0}", i));
              }
          }
      }
      

提交回复
热议问题