如何:绑定到枚举

更新:2007 年 11 月

本示例演示如何通过绑定到枚举的 GetValues 方法来绑定到该枚举。

示例

在下面的示例中,ListBox 通过数据绑定显示 HorizontalAlignment 枚举值的列表。 ListBoxButton 绑定,这样,您可以通过在 ListBox 中选择一个值来更改 ButtonHorizontalAlignment 属性值。

<Window
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:sys="clr-namespace:System;assembly=mscorlib" 
  SizeToContent="WidthAndHeight" 
  Title="Show Enums in a ListBox using Binding">

  <Window.Resources>
    <ObjectDataProvider MethodName="GetValues"
                        ObjectType="{x:Type sys:Enum}"
                        x:Key="AlignmentValues">
      <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="HorizontalAlignment" />
      </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
  </Window.Resources>

  <Border Margin="10" BorderBrush="Aqua"
          BorderThickness="3" Padding="8">
    <StackPanel Width="300">
      <TextBlock>Choose the HorizontalAlignment value of the Button:</TextBlock>
      <ListBox Name="myComboBox" SelectedIndex="0" Margin="8"
               ItemsSource="{Binding Source={StaticResource AlignmentValues}}"/>
      <Button Content="Click Me!"
              HorizontalAlignment="{Binding ElementName=myComboBox,
                                            Path=SelectedItem}"/>
    </StackPanel>
  </Border>
</Window>

请参见

任务

如何:绑定到方法

概念

数据绑定概述

其他资源

数据绑定示例

数据绑定帮助主题