Introduction
By default, WPF does not support Radio button list box like old Win Form Radio Button List. Here this blog describes how to create custom control or Radio List Box in WPF with help of XAML Code.
Getting Started
As we know that WPF does not have Radio Button List Box like Win form. But it can be created by customized the existing List Box control with help of item template of List Box control, data template for binding and Radio Button.WPF provides Template for customize the structure and appearance of existing control same as the List box has item template where you can change structure of items to be display inside the list box. The item control of List box normally used place a control to display control like text box, button etc as item of list box. hence here I have used List Box item template to display radio button in site list box item.
For displaying data or text in item, the data template of WPF is used here. Data Template is used to display content of control or customize the data inside the controls. A Data Template to specify the visualization of your data objects. Data Template objects are particularly useful when you are binding an Items Control such as a List Box to an entire collection. Without specific instructions, a List Box displays the string representation of the objects in a collection. In that case, you can use a Data Template to define the appearance of your data objects. The content of your Data Template becomes the visual structure of your data objects.
The below code example creates a custom radio button list box control, it supports all the feature as like Win Form Radio Button List has and WPF feature like binding. This example lists out students in list and displays name of students with radio button.
XAML Code:
<ListBox Name="listBoxZone" >
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"></RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#Code:
private void FillList()
{
Students.Add(new Student() { Name = "Student1", IsSelected = false });
Students.Add(new Student() { Name = "Student2", IsSelected = false });
Students.Add(new Student() { Name = "Student3", IsSelected = false });
Students.Add(new Student() { Name = "Student4", IsSelected = false });
Students.Add(new Student() { Name = "Student5", IsSelected = false });
this.listBoxZone.ItemsSource = this.Students;
}
Thanks
Kailash Chandra Behera
Comments
Post a Comment