2013-12-17 39 views
2

我有一個組合框以下的(工作)XAML:指定轉換器組合框

<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Converter={StaticResource MyEnumToStringConverter}}"/> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

我不喜歡這樣的代碼:爲了改變我的枚舉是如何表示爲一個字符串,我也有指定ComboBox ItemTemplate的外觀。如果我想要全局更改所有ComboBoxes的外觀,該怎麼辦?

另一種解決方案是指定的的ItemSource轉換器結合:

<ComboBox 
    SelectedValue="{Binding SelectedItem}" 
    ItemsSource="{Binding Items, Converter={StaticResource MyEnumToStringConverter}}" /> 

我不喜歡這樣,因爲任何我想要的組合框來存儲我真正的類型,而不是它的字符串表示。

我還有其他的替代方案嗎?

+1

您可以使用'樣式'來全局更改所有組合框的外觀。 – VS1

+0

@ VS1 True。我想這是一個壞榜樣。實際上困擾我的是如何將枚舉轉換爲字符串,以及如何使用TextBlock進行演示。 –

+0

您可以在您的課堂上創建一個計算出的屬性,並將其用作ComboBox的DisplayMemberPath。 – AjS

回答

0

OP在這裏。我重新提出了也適用於這個問題的heregot an answer這個問題。

1

沒有必要設置每個組合框的ItemTemplate,無論是否在樣式中。

相反,你可以簡單地通過設置DataType屬性創建枚舉類型的默認的DataTemplate

<Window.Resources> 
    <local:MyEnumStringConverter x:Key="MyEnumStringConverter"/> 
    <DataTemplate DataType="{x:Type local:MyEnum}"> 
     <TextBlock Text="{Binding Converter={StaticResource MyEnumStringConverter}}"/> 
    </DataTemplate> 
    ... 
</Window.Resources> 
0

您可以創建一個返回枚舉值的Description屬性值,並結合新的MyEnumText字符串基於屬性的TextBlock.Text屬性,如下所示:

<ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}"> 
<ComboBox.ItemTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding MyEnumText}"/> <!--Bound to new Text property--> 
    </DataTemplate> 
</ComboBox.ItemTemplate> 

添加DescriptionAtrribute屬性到您的枚舉值:

public enum MyEnum 
{ 
    [System.ComponentModel.Description("Value One")] 
    MyValue1 = 1, 

    [System.ComponentModel.Description("Value Two")] 
    MyValue2 = 2, 

    [System.ComponentModel.Description("Value Three")] 
    MyValue3 = 3 
} 

Enum類創建一個擴展方法

public static class EnumHelper 
{ 
    public static string GetDescription(this Enum value) 
    { 
     Type type = value.GetType(); 
     string name = Enum.GetName(type, value); 
     if (name != null) 
     { 
      System.Reflection.FieldInfo field = type.GetField(name); 
      if (field != null) 
      { 
       System.ComponentModel.DescriptionAttribute attr = 
         Attribute.GetCustomAttribute(field, 
         typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute; 
       if (attr != null) 
       { 
        return attr.Description; 
       } 
      } 
     } 
     return null; 
    } 
} 

添加新的屬性MyEnumText它返回一個字符串,您的視圖模型:

public MyEnum MyEnumProperty { get; set; } 

public string MyEnumText //New Property 
{ 
    get 
    { 
     return MyEnumProperty.GetDescription(); 
    } 
}