Sunday, November 1, 2009

WPF Data Binding with Radio Buttons


This is a simple example of data binding using the selection of radio buttons.

The Data selected is picked up by an object label.

To achieve this four classes are needed:

  • <ListBox><ListBox> is nesting the <ListBoxItem> < ListBoxItem >
  • <ListBoxItem><ListBox>is nesting the<RadioButton><RadioButton>
  • <RadioButton><RadioButton>
  • <Label/> is not nested

<ListBox x:Name="RadioButtonList"> the name will be used by the Label.

x:Name is not a property on the ListBox class. It is a special attribute that provides a unique identifier to the object. This x:Name will be used by <Label/> to get its Content.

<ListBoxItem IsSelected="{Binding IsChecked, ElementName=RadioButtonA}"/> The dependency property ListBoxItem.IsSelected=true if the specific radio button is checked. ListBoxItem.IsSelected is true if the specific radio button is checked.

The ElementName=RadioButtonA must have the exact same as the <RadioButton>

<RadioButton x:Name="RadioButtonA">A<RadioButton>

<RadioButton x:Name="RadioButtonB">B<RadioButton>

...

...

...

<RadioButton x:Name="RadioButtonX">XRadioButton>

<Label Content="{Binding SelectedItem.Content.Content, ElementName=RadioButtonList}" Background="SkyBlue" Height="30" />

The Content property, a string is set from the selection of above objects. As observed the ElementName=RadioButtonList has to match with x:Name on the <ListBox>.

Exe is bellow.

http://www.daringa.com/blog/2009/11/WPF_Data_Binding_RadioButton/WPF_DB_RADIOBUTTON.exe

and source file

http://www.daringa.com/blog/2009/11/WPF_Data_Binding_RadioButton/WpfApplication5.zip


1 comment:

  1. Really interesting stuff ... I wish you'd post more about this.

    ReplyDelete