WPF Binding ItemsSource to Enum

通过ObjectDataProvider 获取Enum数据源。


1. 定义一个Enum类

public enum SampleEnum
{
     Dog,
     Cat,
     Scrat,
     Hefalump
}


2. 在Xaml中的Resource里定义数据源,并定义 x:Key="dataFromEnum"

<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>


3. 指定ItemsSource

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
     }
}
    
    结果截图:
WPF Binding ItemsSource to Enum
 
 参考:http://weblogs.asp.net/monikadyrda/wpf-binding-itemssource-to-enum 
 

你可能感兴趣的:(enum,ListView,combobox,WPF,binding)