There are 2 lists - AvailableItems and SelectedItems.
AvailableItems is displayed in a ListBox, and each ListBoxItem contains a CheckBox. The intention is that the CheckBox is checked if the bound item is in SelectedItems.
Can I achieve this without handling Checked and Unchecked in the code-behind, and without adding an IsSelected property to my item class?
Here's the XAML so far:
<ListBox Name="ListBox1" ItemsSource="{Binding Path=AvailableItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<DockPanel>
<CheckBox Name="cb1"></CheckBox>
<TextBlock Text="{Binding}"></TextBlock>
</DockPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
and the code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
_availableItems.Add(Colors.Red);
_availableItems.Add(Colors.Green);
_availableItems.Add(Colors.Blue);
_selectedItems.Add(Colors.Green);
this.DataContext = this;
}
ObservableCollection<Color> _selectedItems = new ObservableCollection<Color>();
public ObservableCollection<Color> SelectedItems
{
get { return _selectedItems; }
set { _selectedItems = value; }
}
ObservableCollection<Color> _availableItems = new ObservableCollection<Color>();
public ObservableCollection<Color> AvailableItems
{
get { return _availableItems; }
set { _availableItems = value; }
}
}
The above xaml/code can be copied straight into a new WPF project for testing.