2013-11-01 93 views
2

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

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

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绑定到枚举。

+0

准确的目标是什么?只需将选项卡标题绑定到枚举值? – McGarnagle

+0

是的ans还有一种常见的方法来获取可用于绑定到任何控件的枚举值。如使用ObjectDataProvied或使用转换器。 – SoftDev

+0

嗯,我认为#2应该可以工作 - 但是你不需要双向绑定,并实现“ConvertBack”方法吗? – McGarnagle

回答

3

这里做的更好的方式:

在你的模型,把这个属性:

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

(随意的名称更改为任何适合你,但只记得到处更改)

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

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

这将需要从你的YourEnumTypeHere所有的名字,让他们对你有约束力的财产在你的XAML这样的:

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

现在,很明显,它并没有成为一个列表框,但现在你只是绑定到一个字符串集合,你的问题应该被解决。