mac*_*nir 4 data-binding wpf combobox
我将WPF ComboBox绑定到MyEnum类型的可空属性?(其中MyEnum是枚举类型)
我以编程方式填充ComboBox项目,如下所示:
// The enum type being bound to
enum MyEnum { Yes, No }
// Helper class for representing combobox listitems
// (a combination of display string and value)
class ComboItem {
public string Display {get;set}
public MyEnum? Value {get;set}
}
private void LoadComboBoxItems()
{
// Make a list of items to load into the combo
var items = new List<ComboItem> {
new ComboItem {Value = null, Display = "Maybe"},
new ComboItem {Value = MyEnum.Yes, Display = "Yes"},
new ComboItem {Value = MyEnum.No, Display = "No"},};
// Bind the combo's items to this list.
theCombo.ItemsSource = items;
theCombo.DisplayMemberPath = "Display";
theCombo.SelectedValuePath = "Value";
}
Run Code Online (Sandbox Code Playgroud)
同样在代码隐藏中,我将DataContext设置为一个类的实例,该类具有一个名为TheNullableProperty的属性(对于此示例,无论如何),类型为MyEnum?.
Combo的SelectedValue的绑定在我的XAML文件中完成.
<ComboBox
Name="theCombo"
SelectedValue="{Binding Path=TheNullableProperty,
UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)
问题:
当bound属性的值最初为非null时,组合框会正确显示该值.
但是当bound属性的值最初为null时,组合框为空.
看起来数据绑定的每个方面都与首次显示组合框时的空值表示不同.
例如:您可以从下拉列表中选择Maybe,并将bound属性正确设置为null.只是初始加载失败了.也许我需要最初手动设置SelectedValue ...
将组合框数据绑定到文本块.
/// <summary>
/// Convert from EnumeratedType? to string (null->"null", enum values->ToString)
/// </summary>
public class EnumConverter<T> : IValueConverter where T:struct
{
public static string To(T? c)
{
if (c == null)
return "null";
return c.ToString();
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return To((T?)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var s = (string) value;
if (s == "null")
return null;
return (T?)Enum.Parse(typeof(T), s);
}
}
public class MyEnumConverter : EnumConverter<MyEnum>
{
}
public class ComboItem
{
public string Value { get; set; }
public string Label { get; set; }
public ComboItem(MyEnum? e, string label)
{
Value = MyEnumConverter.To(e);
Label = label;
}
}
static IEnumerable<ComboItem> GetItems()
{
yield return new ComboItem(null, "maybe");
yield return new ComboItem(MyEnum.Yes, "yup");
yield return new ComboItem(MyEnum.No, "nope");
}
private void SetupComboBox()
{
thecombo.ItemsSource = GetItems().ToList();
}
Run Code Online (Sandbox Code Playgroud)您无法在WPF(至少3.5 SP1)中按设计绑定到空值.这意味着,当Source获取Null作为值时,您的Binding将自动被破坏,即使您为Source指定了有效值也无法工作.您需要通过Value Converter为您的绑定提供一些"心脏跳动"机制.因此,Converter将null值转换为Targets的某些"Undefined"(非null),并且能够将"Undefined"转换回null ...
| 归档时间: |
|
| 查看次数: |
11884 次 |
| 最近记录: |