【问题标题】:combobox databinding to selectedvalue event组合框数据绑定到 selectedvalue 事件
【发布时间】:2011-12-16 22:47:36
【问题描述】:

当用户在组合框中选择不同的值时,我想执行一些功能。

我正在使用 MVVM 模式。

知道在这种情况下我如何绑定数据吗?

【问题讨论】:

    标签: c# wpf data-binding mvvm combobox


    【解决方案1】:

    绑定到 SelectedItem 上的属性。 在属性的设置器中,执行您的函数。 SelectedItem="{Binding Path=SomeProperty}"

    【讨论】:

      【解决方案2】:

      您可能希望绑定到SelectedValueSelectedItemSelectedIndex,具体取决于您要执行的操作:

      public class MyViewModel : INotifyPropertyChanged
      {
          public ObservableCollection<MyObj> MyCollection { get; private set; }
      
          private MyObj _theItem;
          public MyObj TheItem
          {
              get { return _theItem; }
              set
              {
                  if (Equals(value, _theItem)) return;
      
                  _theItem= value;
      
                  //Or however else you implement this...
                  OnPropertyChanged("TheItem");
                  //Do something here.... OR
                  //This will trigger a PropertyChangedEvent if you're subscribed internally.
              }
          }
      
          private string _theValue;
          public string TheValue
          {
              get { return _theValue; }
              set
              {
                  if (Equals(value, _theValue)) return;
      
                  _theValue= value;
                  OnPropertyChanged("TheValue");
              }
          }
      
          private int _theIndex;
          public int TheIndex
          {
              get { return _theIndex; }
              set
              {
                  if (Equals(value, _theIndex)) return;
      
                  _theIndex = value;
                  OnPropertyChanged("TheIndex");
              }
          }
      }
      
      public class MyObj
      {
          public string PropA { get; set; }
      }
      
       <!-- Realistically, you'd only want to bind to one of those -->
       <!-- Most likely the SelectedItem for the best usage -->
       <ItemsControl ItemsSource="{Binding Path=MyCollection}"
                     SelectedItem="{Binding Path=TheItem}"
                     SelectedValue="{Binding Path=TheValue}"
                     SelectedIndex="{Binding Path=TheIndex}"
                     />
      

      【讨论】:

        猜你喜欢
        • 2017-11-16
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 2015-07-11
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        相关资源
        最近更新 更多