将WPF ComboBox绑定到枚举和隐藏某些值

时间:2014-01-08 14:05:31

标签: wpf binding combobox enums

我有一个WPF组合框,它绑定到这样的枚举:

<Window.Resources>
    <local:EnumDescriptionConverter x:Key="enumDescriptionConverter"/>
    <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="cityNamesDataProvider">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:MyModel+CityNamesEnum"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

<ComboBox x:Name="cityNameComboBox" ItemsSource="{Binding Source={StaticResource cityNamesDataProvider}}" SelectionChanged="cityNameComboBox_SelectionChanged">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource enumDescriptionConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

我绑定的枚举具有描述属性,如下所示:

public enum CityNamesEnum
{
    [Description("New York City")]
    NewYorkCity,
    [Description("Chicago")]
    Chicago,
    [Description("Los Angeles")]
    LosAngeles
}

我并不总是希望显示每个枚举值。是否可以切换一个或多个枚举值的可见性?如果这些是ComboBoxItems,我想我可以简单地将.Visibility属性设置为隐藏,但由于它们是枚举值,我不确定这是否可行。有谁知道吗?

1 个答案:

答案 0 :(得分:7)

为什么不创建一个普通的C#方法,为您进行过滤,然后让ObjectDataProvider指向该方法呢

static method IEnumerable<CityNamesEnum> MyFilter() {
  yield return CityNames.NewYorkCity;
  yield return CityNames.Chicago;
}

XAML

<ObjectDataProvider 
   MethodName="MyFilter" 
   ObjectType="{x:Type local:TheType}" 
   x:Key="cityNamesDataProvider">
</ObjectDataProvider>