更新时间:2022-10-21 11:07:19
您可以通过将代码放在Window 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 =dataFromEnumMethodName =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 。
I am trying to find a simple example where the enums are shown as is. All examples I have seen tries to add nice looking display strings but I don't want that complexity.
Basically I have a class that holds all the properties that I bind, by first setting the DataContext to this class, and then specifying the binding like this in the xaml file:
<ComboBox ItemsSource="{Binding Path=EffectStyle}"/>
But this doesn't show the enum values in the ComboBox
as items.
You can do it from code by placing the following code in Window Loaded
event handler, for example:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();
If you need to bind it in XAML you need to use ObjectDataProvider
to create object available as binding source:
<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>
Draw attention on the next code:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
Guide how to map namespace and assembly you can read on MSDN.