2

在我的程序(MVVM WPF)中有很多枚举,我将枚举绑定到视图中的控件。

有很多方法可以做到这一点。

1) 绑定到 ComboBoxEdit(Devexpress Control)。我正在使用 ObjectDataProvider。

然后这个

<dxe:ComboBoxEdit ItemsSource="{Binding Source={StaticResource SomeEnumValues}>

这可以正常工作,但在 TabControl 标头中却不行。

2)所以,我想到了使用也没有用的 IValueConverter。

public object Convert(object value, Type targetType, object parameter, 
    CultureInfo culture)
{
    if (!(value is Model.MyEnum))
    {
        return null;
    }

    Model.MyEnum me = (Model.MyEnum)value;
    return me.GetHashCode();
}

public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
{
    return null;
}

在 XAML 上:

<local:DataConverter x:Key="myConverter"/>

<TabControl SelectedIndex="{Binding Path=SelectedFeeType, 
      Converter={StaticResource myConverter}}"/>

3) 第三种方法是做一个行为依赖属性

像这样的东西

public class ComboBoxEnumerationExtension : ComboBox
    {
        public static readonly DependencyProperty SelectedEnumerationProperty =  
          DependencyProperty.Register("SelectedEnumeration", typeof(object), 
          typeof(ComboBoxEnumerationExtension));

        public object SelectedEnumeration
        {
            get { return (object)GetValue(SelectedEnumerationProperty); }
            set { SetValue(SelectedEnumerationProperty, value); }
        }

我想知道处理枚举和绑定它的最佳方式是什么。现在我无法将 tabheader 绑定到枚举。

4

1 回答 1

3

这是一个更好的方法:

在您的模型上,放置此属性:

public IEnumerable<string> EnumCol { get; set; }

(随意将名称更改为适合您的名称,但请记住在任何地方更改)

在构造函数中有这个(或者更好的是,把它放在一个初始化方法中):

var enum_names = Enum.GetNames(typeof(YourEnumTypeHere));
EnumCol = enum_names ;

这将从您那里获取所有名称,YourEnumTypeHere并将它们放在您将在 xaml 中绑定到的属性上,如下所示:

<ListBox ItemsSource="{Binding EnumCol}"></ListBox>

现在,显然,它不必是 ListBox,但现在您只是绑定到字符串集合,您的问题应该得到解决。

于 2013-11-03T01:51:58.687 回答