I have a ComboBox
with its ItemsSource
set to an IList
of MyClass
objects. I overrode the ComboBox
's ItemTemplate
to display a CheckBox
next to the items. I want to have an item at the top that says "Select All" and when the user checks that CheckBox
, the code checks all CheckBoxes
. My question is, what is the MVVM way of doing this?
I don't want to add a separate MyClass
object to the IList
. That seems like it would involve too much coupling of the view and the model. Is there a way to add an item directly in the XAML code and give it a Command
that checks all of the Checkboxes
?
My ComboBox
XAML right now is:
<ComboBox ItemsSource="{Binding MyList}" Width="200">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding Selected}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
That looks like:
I'd like it to look like:
My MyClass is simply this:
public class MyClass
{
public string Name { get; set; }
public bool Selected { get; set; }
}
Edit: I found a way to add an item to the collection in the XAML code using the example here. I would still need a way run code when the user checks the checkbox for that "Select All" item. To just add the item, the code is this:
<ComboBox Width="200">
<ComboBox.Resources>
<CollectionViewSource x:Key="comboBoxSource" Source="{Binding Path=MyList}" />
</ComboBox.Resources>
<ComboBox.ItemsSource>
<CompositeCollection>
<local:MyClass Name="Select All" Selected="False">
</local:MyClass>
<CollectionContainer Collection="{Binding Source={StaticResource comboBoxSource}}" />
</CompositeCollection>
</ComboBox.ItemsSource>
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding Selected}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>