Rough layout using MVVM
create a class to represent all the data needed for each item, for example, Checked and Description
class CustomItem : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool _isSelected; private string _customColour; public bool IsSelected { get { return _isSelected; } set { _isSelected = value; if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("IsSelected")); } } } public string CustomColour { get { return _customColour; } set { _customColour = value; if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("CustomColour")); } } } }
create a class to represent the collection of elements you want to display
class CustomItems : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private ObservableCollection<CustomItem> _listOfCustomItems; public CustomItems() { ListOfCustomItems = new ObservableCollection<CustomItem>(); var c = new CustomItem { IsSelected = false, CustomColour = "Red" }; ListOfCustomItems.Add(c); c = new CustomItem { IsSelected = true, CustomColour = "Green" }; ListOfCustomItems.Add(c); c = new CustomItem { IsSelected = false, CustomColour = "Blue" }; ListOfCustomItems.Add(c); } public ObservableCollection<CustomItem> ListOfCustomItems { get { return _listOfCustomItems; } set { _listOfCustomItems = value; if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ListOfCustomItems")); } } } public List<CustomItem> SelectedItems { get { return (from customItem in ListOfCustomItems where customItem.IsSelected select customItem).ToList(); } } }
Add to window
<Window.Resources> <WpfApplication1:CustomItems x:Key="CI"/> </Window.Resources> <Grid DataContext="{StaticResource CI}"> <ListBox ItemsSource="{Binding Path=ListOfCustomItems}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel></StackPanel> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <DockPanel> <CheckBox IsChecked="{Binding Path=IsSelected}"/> <TextBlock Text="{Binding Path=CustomColour}"/> </DockPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ListBox> </Grid>
You save one list of items and provide a property for retrieving selects that select a simple LINQ. Easy. Change data types as needed.
source share