通过ObjectDataProvider 获取Enum数据源。
public enum SampleEnum { Dog, Cat, Scrat, Hefalump }
<Window x:Class="WpfApplication1.Window1" 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:local="clr-namespace:WpfApplication1" Title="Bind to Enum" Height="250" Width="250"> <Window.Resources> <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="local:SampleEnum"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> </Window>
ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
此种方法可以用到ListView、Combobox (或者其它的ItemsControl) 上。
完整Xaml代码:
<Window x:Class="WpfApplication1.Window1" 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:local="clr-namespace:WpfApplication1" Title="Bind to Enum" Height="250" Width="250"> <Window.Resources> <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="local:SampleEnum"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> <Grid> <ListView ItemsSource="{Binding Source={StaticResource dataFromEnum}}" Margin="10,10,10,0" Height="80" VerticalAlignment="Top" /> <ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}" Margin="10,0,10,80" Height="25" VerticalAlignment="Bottom" /> </Grid> </Window>
完整后台代码:using System.Windows; namespace WpfApplication1 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } } public enum SampleEnum { Dog, Cat, Scrat, Hefalump } }
结果截图:
参考:http://weblogs.asp.net/monikadyrda/wpf-binding-itemssource-to-enum