我试图找到一个简单的例子,其中枚举按原样显示.我看到的所有示例都试图添加好看的显示字符串,但我不希望这样复杂.
基本上,我有一个类,它保存我绑定的所有属性,首先将DataContext设置为这个类,然后在xaml文件中指定如下绑定:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>
但是这不会将ComboBox
中的枚举值显示为项.
我试图找到一个简单的例子,其中枚举按原样显示.我看到的所有示例都试图添加好看的显示字符串,但我不希望这样复杂.
基本上,我有一个类,它保存我绑定的所有属性,首先将DataContext设置为这个类,然后在xaml文件中指定如下绑定:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>
但是这不会将ComboBox
中的枚举值显示为项.
您可以通过在Windows Loaded
事件处理程序中放置以下代码,从代码中执行此操作,例如:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();
如果需要在XAML中绑定它,则需要使用ObjectDataProvider
来创建可用作绑定源的对象:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="StyleAlias:EffectStyle"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
SelectedItem="{Binding Path=CurrentEffectStyle}" />
</Grid>
</Window>
请注意下面的代码:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
指导如何映射命名空间和程序集,您可以在MSDN上阅读.