Cancel combobox selection in WPF with MVVM

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

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



        
12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 11:05

    I think the problem is that the ComboBox sets the selected item as a result of the user action after setting the bound property value. Thus the Combobox item changes no matter what you do in the ViewModel. I found a different approach where you don't have to bend the MVVM pattern. Here's my example (sorry that it is copied from my project and does not exactly match the examples above):

    public ObservableCollection Styles { get; }
    
    public StyleModelBase SelectedStyle {
      get { return selectedStyle; }
      set {
        if (value is CustomStyleModel) {
          var buffer = SelectedStyle;
          var items = Styles.ToList();
          if (openFileDialog.ShowDialog() == true) {
            value.FileName = openFileDialog.FileName;
          }
          else {
            Styles.Clear();
            items.ForEach(x => Styles.Add(x));
            SelectedStyle = buffer;
            return;
          }
        }
        selectedStyle = value;
        OnPropertyChanged(() => SelectedStyle);
      }
    }
    

    The difference is that I completely clear the items collection and then fill it with the items stored before. This forces the Combobox to update as I'm using the ObservableCollection generic class. Then I set the selected item back to the selected item that was set previously. This is not recommended for a lot of items because clearing and filling the combobox is kind of expensive.

提交回复
热议问题