【问题标题】:Windows Forms ComboBox - case insensitive data-bindingWindows Forms ComboBox - 不区分大小写的数据绑定
【发布时间】:2010-09-13 19:42:31
【问题描述】:

如果我正在对一个 winforms 组合框进行数据绑定,有没有办法使绑定不区分大小写?

例如,如果组合框绑定到值为 FOO 的属性,让它选择值为 Foo 的组合框项?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    不,这是不可能的。这是使用区分大小写的反射在内部实现的。

    【讨论】:

      【解决方案2】:

      游戏有点晚了,但这是我为允许不区分大小写绑定到 WinForms ComboBox 所做的:

      我创建了自己的继承自 ComboBox 的类,并添加了以下属性以将我的数据绑定到(请原谅来自 VB.NET 的自动转换):

      public object Value {
          get {
              if (string.IsNullOrEmpty(ValueMember)) {
                  return Text;
              } else {
                  return SelectedValue;
              }
          }
          set {
              if (DesignMode)
                  return;
      
              // If we're databound, Value is the SelectedValue.  Otherwise, it's the Text.
              object oldValue = string.IsNullOrEmpty(ValueMember) ? Text : SelectedValue;
      
              // Want to make sure we're comparing apples to apples, and not specific instances of apples.
              string strOld = oldValue == null ? string.Empty : Convert.ToString(oldValue);
              string strNew = value == null ? string.Empty : Convert.ToString(value);
      
              if (!string.Equals(strOld, strNew, StringComparison.OrdinalIgnoreCase)) {
                  if (ValueMember.HasValue) {
                      if (value != null && !string.IsNullOrEmpty(Convert.ToString(value))) {
                          SelectedItem = Items.OfType<object>.FirstOrDefault((System.Object i) => string.Equals(Convert.ToString(FilterItemOnProperty(i, ValueMember)), strNew, StringComparison.OrdinalIgnoreCase));
                      } else {
                          SelectedIndex = -1;
                      }
                  } else {
                      Text = value != null ? value.ToString : string.Empty;
                  }
                  ValidateField();
                  if (PropertyChanged != null) {
                      PropertyChanged(this, new PropertyChangedEventArgs("Value"));
                  }
              }
          }
      }
      

      ValidateField 是一个您可以忽略的自定义方法,但您需要为 Value 属性实现 INotifyPropertyChanged

      【讨论】:

      • 请注意,您在上述代码中绑定到 Value 属性的数据类型应该是基本值类型(或 String)而不是复杂对象,否则 Convert.ToString 可能会返回两个不同对象的相同字符串(表示对象类型的字符串,如果对象的类没有覆盖 .ToString 方法)。由于您可能使用它来将数据库行中的字段绑定到 ComboBox 的 DataSource 集合/表中的属性或字段,因此这应该不是问题。
      猜你喜欢
      • 1970-01-01
      • 2016-08-29
      • 2014-08-01
      • 1970-01-01
      • 2015-06-14
      • 2022-01-25
      • 2013-11-02
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多