问题
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
}
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?
回答1:
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>
来源:https://stackoverflow.com/questions/20997898/binding-wpf-combobox-to-enum-and-hiding-certain-values