将 WPF ComboBox 绑定到枚举并隐藏某些值 [英] Binding WPF ComboBox to enum and hiding certain values

查看:39
本文介绍了将 WPF ComboBox 绑定到枚举并隐藏某些值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到枚举的 WPF 组合框,如下所示:

I have a WPF combobox that is bound to an enum like this:

<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>

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

The enum that I'm binding to has description attributes and looks like this:

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

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

I don't always want to display each enum value. Is it possible to toggle the visibility of one or more of the enum values? If these were ComboBoxItems, I think I could simply set the .Visibility property to hidden but since they're enum values, I'm not sure if this is possible. Does anyone know?

推荐答案

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

Why not just create a normal C# method which does the filtering for you and then have the ObjectDataProvider point to that method instead

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>

这篇关于将 WPF ComboBox 绑定到枚举并隐藏某些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆