I am looking for a WPF combo box with checkboxes. I reffered to the below link and used the solution given by Sergey. Looking for a WPF ComboBox with checkboxes
The solution provided works fine but I am not sure how the binding to the combo box is done. I am new to WPF so it would be great if I could get any help on this. XAML code:
<Window x:Class="WpfApplication1.StackCombo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="StackCombo" Height="338" Width="533">
<Grid>
<ComboBox Name="cbObjects" VerticalAlignment="Center" Margin="103,140,280,138" SelectionChanged="OnCbObjectsSelectionChanged" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsSelected}" Width="20" VerticalAlignment="Center" Checked="OnCbObjectCheckBoxChecked" Unchecked="OnCbObjectCheckBoxChecked" />
<TextBlock Text="{Binding}" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock IsHitTestVisible="False" Name="tbObjects" Text="None" VerticalAlignment="Center" Margin="113,100,268,184" />
</Grid>
This is the code Behind:
public partial class StackCombo : Window
{
public StackCombo()
{
ObservableCollection<SelectableObject<Person>> _list;
InitializeComponent();
_list = new ObservableCollection<SelectableObject<Person>>();
_list.Add(new SelectableObject<Person>(new Person("DEF")));
cbObjects.ItemsSource = _list;
}
private class Person
{
public Person(String firstName)
{
this.firstName=firstName;
}
private String firstName;
public String FirstName
{
get { return firstName; }
set { firstName = value; }
}
}
public class SelectableObject<T>
{
public bool IsSelected { get; set; }
public T ObjectData { get; set; }
public SelectableObject(T objectData)
{
ObjectData = objectData;
}
public SelectableObject(T objectData, bool isSelected)
{
IsSelected = isSelected;
ObjectData = objectData;
}
}
private void OnCbObjectCheckBoxChecked(object sender, RoutedEventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (SelectableObject<Person> cbObject in cbObjects.Items)
if (cbObject.IsSelected)
sb.AppendFormat("{0}, ", cbObject.ObjectData.FirstName);
tbObjects.Text = sb.ToString().Trim().TrimEnd(',');
}
private void OnCbObjectsSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
comboBox.SelectedItem = null;
}
}
Thanks, Ramkumar