2013-11-01 133 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> 

現在,很明顯,它並沒有成爲一個列表框,但現在你只是綁定到一個字符串集合,你的問題應該被解決。