星期三, 5月 02, 2007

[WPF] Displaying Enum Values using Data Binding

--> DataBinding 到enum valuem, Copy & Paste如下

Some of the FAQs about data binding are:

• How do I bind to a method?

• How do I bind between instantiated controls?

• How do I bind an ItemsControl to an enum?



I put together a quick sample that should answer the above questions:



<Window



  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"



  xmlns:x="http://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>



The ListBox and the Button are hooked up such that you can “control”

the HorizontalAlignment value of the Button by selecting a value in the

ListBox.

沒有留言: