【发布时间】:2010-09-13 19:42:31
【问题描述】:
如果我正在对一个 winforms 组合框进行数据绑定,有没有办法使绑定不区分大小写?
例如,如果组合框绑定到值为 FOO 的属性,让它选择值为 Foo 的组合框项?
【问题讨论】:
如果我正在对一个 winforms 组合框进行数据绑定,有没有办法使绑定不区分大小写?
例如,如果组合框绑定到值为 FOO 的属性,让它选择值为 Foo 的组合框项?
【问题讨论】:
不,这是不可能的。这是使用区分大小写的反射在内部实现的。
【讨论】:
游戏有点晚了,但这是我为允许不区分大小写绑定到 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。
【讨论】: