Feeds:
Posts
Comments

Archive for December, 2010

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 »

The BindingBase.StringFormat property was included with the .NET framework 4.0 and is quite a handy feature. I recently found myself going back through old projects to remove binding converters and replace their logic with the StringFormat property. There is a decent example on the MSDN here. However, I felt like expanding on it a bit so here goes.

First I have created a Person class that has some basic properties like FirstName, LastName, Age, etc. Here is the code for the Person class and enum it uses.

using System;
using System.ComponentModel;

namespace BindingStringFormat
{
     public enum Sex
     {
          male,
          female
     }

     public class Person : INotifyPropertyChanged
     {
          #region Properties

          public string FirstName
          {
               get { return _firstName; }
               set { _firstName = value; OnPropertyChanged("FirstName"); }
          }private string _firstName;

          public string LastName
          {
               get { return _lastName; }
               set { _lastName = value; OnPropertyChanged("LastName"); }
          }private string _lastName;

          public int Age
          {
               get { return _age; }
               set { _age = value; OnPropertyChanged("Age"); }
          }private int _age;

          public DateTime BirthDate
          {
               get { return _birthDate; }
               set { _birthDate = value; OnPropertyChanged("BirthDate"); }
          }private DateTime _birthDate;

          public Sex Sex
          {
               get { return _sex; }
               set { _sex = value; OnPropertyChanged("Sex"); }
          }private Sex _sex;

          #endregion

          #region Constructor(s)

          public Person() { }

          public Person(string lastName, string firstName, int age, DateTime birthDate, Sex sex)
          {
               this.FirstName = firstName;
               this.LastName = lastName;
               this.Age = age;
               this.BirthDate = birthDate;
               this.Sex = sex;
          }

          #endregion

          #region INotifyPropertyChanged Members

          public event PropertyChangedEventHandler PropertyChanged;

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

          #endregion
     }
}

Next is the MainWindow. I have created a public Person property in the code behind and set the DataContext of the MainWindow.xaml to the Person property. Here is the code for that.

using System;
using System.Windows;

namespace BindingStringFormat
{
     /// <summary>
     /// Interaction logic for MainWindow.xaml
     /// </summary>
     public partial class MainWindow : Window
     {
          public Person Person
          {
               get
               {
                    if (_person == null)
                         _person = new Person("Bob", "Billy", 29, new DateTime(1978, 3, 9), Sex.male);

                    return _person;
               }
               set
               {
                    _person = value;
               }
          }private Person _person;

          public MainWindow()
          {
               InitializeComponent();
               this.DataContext = Person;
          }
     }
}

Last but not least is the MainWindow.xaml which is where the StringFormat syntax lies. In this example you will notice I have bound a string, integer, enum, and date to some TextBlocks and customized their display with the StringFormat property. I especially like the ability to use StringFormat with MultiBinding, and as I said before, this should help you get rid of some now obsolete BindingConverters. Enjoy!


<Window x:Class="BindingStringFormat.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

   <Grid Margin="25">
        <StackPanel>
             <TextBlock Margin="5">
                  <TextBlock.Text>
                       <MultiBinding StringFormat="Hello {0} {1}!">
                            <Binding Path="FirstName"/>
                            <Binding Path="LastName"/>
                       </MultiBinding>
                  </TextBlock.Text>
             </TextBlock>
             <TextBlock Text="{Binding Path=Age, StringFormat='You are {0} years old.'}" Margin="5"/>
             <TextBlock Text="{Binding Path=Sex, StringFormat='You are a {0}.'}" Margin="5"/>
             <TextBlock Text="{Binding Path=BirthDate, StringFormat='You were born on {0:MM/dd/yyyy}'}" Margin="5"/>
        </StackPanel>
   </Grid>

</Window>

Here is what you should see when you run the application:

BindingBase.StringFormat

Read Full Post »