Feeds:
Posts
Comments

Posts Tagged ‘GetValues’

Well I hope the title of this post is fairly self explanatory. In this example I am going to show you how to first populate a ComboBox with the values in an enumeration. I am then going to databind a property of type enum to the SelectedItem of the ComboBox. If you would like to extend the sample and sort the values displayed in the ComboBox I suggest you check out this post by the almighty Josh Smith. Now on to the code.

First off, here is my animal enumeration:

public enum Animal
{
     Bear,
     Cheetah,
     Deer,
     Elehpant,
}

Here is my MainWindow.cs.

public partial class MainWindow : Window, INotifyPropertyChanged
{
     public Animal MyAnimal
     {
          get { return _myAnimal; }
          set
          {
               if (_myAnimal != value)
               {
                    _myAnimal = value;
                    OnPropertyChanged("MyAnimal");
               }
          }
     }private Animal _myAnimal;

     public MainWindow()
     {
          InitializeComponent();
     }

     #region INotifyPropertyChanged Members

     public event PropertyChangedEventHandler PropertyChanged;

     void OnPropertyChanged(string propName)
     {
          if (this.PropertyChanged != null)
               this.PropertyChanged(
                    this, new PropertyChangedEventArgs(propName));
     }

     #endregion
}

Finally, here is the MainWindow.xaml where I am using an ObjectDataProvider and GetValues to provide the content for my ComboBox’s ItemsSource. When you run the app and change the SelectedItem in the ComboBox, you should see the TextBox update with the newly selected animal. Enjoy!

<Window x:Class="ComboBoxBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ComboBoxBinding"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="125" Width="200"
        x:Name="mainWindow">

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

     <Grid Background="LightBlue" DataContext="{Binding ElementName=mainWindow}">
          <StackPanel HorizontalAlignment="Center">
               <ComboBox ItemsSource="{Binding Source={StaticResource Animals}}"
                         SelectedItem="{Binding MyAnimal}"
                         Margin="10"/>

               <TextBox Text="{Binding MyAnimal}" Width="100"/>
          </StackPanel>
     </Grid>
</Window>
Advertisements

Read Full Post »