如何将枚举绑定到 WPF 中的组合框控件? [英] How to bind an enum to a combobox control in WPF?
问题描述
我试图找到一个简单的例子,其中枚举按原样显示.我见过的所有例子都试图添加漂亮的显示字符串,但我不想要那么复杂.
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.
基本上我有一个类来保存我绑定的所有属性,首先将 DataContext 设置为这个类,然后在 xaml 文件中像这样指定绑定:
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}"/>
但这不会将 ComboBox
中的枚举值显示为项目.
But this doesn't show the enum values in the ComboBox
as items.
推荐答案
您可以通过将以下代码放在 Window Loaded
事件处理程序中来从代码中完成,例如:
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>();
如果您需要在 XAML 中绑定它,您需要使用 ObjectDataProvider
创建可用作绑定源的对象:
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>
注意下一个代码:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
指导如何映射命名空间和程序集,您可以在 MSDN 上阅读.
Guide how to map namespace and assembly you can read on MSDN.
这篇关于如何将枚举绑定到 WPF 中的组合框控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!