Dietmar Brueckmann

Dietmar Brueckmann

  • 1.7k
  • 66
  • 1.2k

Build a CheckListBox

Jul 10 2019 6:50 AM
Hello,
 
I've tried to build a usercontrol CheckListBox similar to
https://www.codeproject.com/Tips/1210187/%2FTips%2F1210187%2FA-WPF-CheckBox-ListBox
But this example doesn't show how to bind IsChecked or IsSelected to Viewmodels data.
In the xaml is the line IsChecked="{TemplateBinding IsSelected}" 
I've build an observable list based on simple class "Satz" with IsChecked-property.
The app works, but my IsChecked-property Is'nt used, because I don't know how to connect it to "TemplateBinding IsSelected"
 
 
This is the esentiell Part of the xaml:
 
  1. <ListBox Margin="15"  
  2.            VerticalAlignment="Stretch"  
  3.            ItemsSource="{Binding Items}"  
  4.            SelectionMode="Multiple">  
  5.       <ListBox.Resources>  
  6.           <Style TargetType="ListBoxItem">  
  7.               <Setter Property="OverridesDefaultStyle" Value="true" />  
  8.               <Setter Property="SnapsToDevicePixels" Value="true" />  
  9.               <Setter Property="Template">  
  10.                   <Setter.Value>  
  11.                       <ControlTemplate TargetType="ListBoxItem">  
  12.                           <CheckBox Margin="5,2"  
  13.                                     IsChecked="{TemplateBinding IsSelected}">  
  14.                               <ContentPresenter />  
  15.                           </CheckBox>  
  16.                       </ControlTemplate>  
  17.                   </Setter.Value>  
  18.               </Setter>  
  19.           </Style>  
  20.       </ListBox.Resources>  
  21.   </ListBox>  
and this the part of ViewModel.cs
 
  1. public enum EnumCheckListBox  
  2. {  
  3.     hare, hedgehog, deer, frog, fox, wolf, wild_boar  
  4. }  
  5. public class Satz  
  6. {  
  7.     public EnumCheckListBox What { getset; }  
  8.     public override string ToString()  
  9.     {  
  10.         return What.ToString();  
  11.     }  
  12.     public bool IsChecked { getset; }  
  13. }  
  14. public class ViewModel  
  15. {  
  16.     public ObservableCollection<Satz> Items { get; } = new ObservableCollection<Satz>();  
  17.     public ViewModel()  
  18.     {  
  19.         foreach (EnumCheckListBox enm in Enum.GetValues(typeof(EnumCheckListBox)))  
  20.         {  
  21.             Items.Add(new Satz {  
  22.                 What = enm,  
  23.                 IsChecked = enm == EnumCheckListBox.deer  
  24.             });  
  25.         }          
  26.     }  
  27. }  
 
 
 
 
best regards Dietmar 
 
 

Attachment: TestCheckListBox.zip

Answers (1)