WPF: get ListBoxItem as CheckBox with Style template for synchronization with IsSelected

I am creating an MVV MVVM application, in this application I have a ListBox with my own privileged items.

After centuries, I finally found a solution to get choices synchronized with my ViewModel. (You also need to implement IEquatable in your product class)

Problem

Now I want to style ListBoxItems as CheckBoxes, there are many solutions for this problem, but none of them meet my needs.

So, I came up with this solution because I can only apply this style to the ListBox that I need, and I don’t have to worry about DisplayMemberPath or that the items were in the style of CheckBox and ListBoxItems.

View:

<ListBox Grid.Row="5" Grid.Column="1" ItemsSource="{Binding Privileges}" BehavExt:SelectedItems.Items="{Binding SelectedPrivileges}" SelectionMode="Multiple" DisplayMemberPath="Name" Style="{StaticResource CheckBoxListBox}"/> 

Style:

 <Style x:Key="CheckBoxListBox" TargetType="{x:Type ListBox}" BasedOn="{StaticResource MetroListBox}"> <Setter Property="Margin" Value="5" /> <Setter Property="ItemContainerStyle" Value="{DynamicResource CheckBoxListBoxItem}" /> </Style> <Style x:Key="CheckBoxListBoxItem" TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource MetroListBoxItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <CheckBox IsChecked="{TemplateBinding Property=IsSelected}"> <ContentPresenter /> </CheckBox> </ControlTemplate> </Setter.Value> </Setter> </Style> 

ViewModel:

 private ObservableCollection<Privilege> _privileges; public ObservableCollection<Privilege> Privileges { get { return _privileges; } set { _privileges = value; RaisePropertyChanged(() => Privileges); } } private ObservableCollection<Privilege> _selectedPrivileges; public ObservableCollection<Privilege> SelectedPrivileges { get { return _selectedPrivileges; } set { _selectedPrivileges = value; RaisePropertyChanged(() => SelectedPrivileges); } } 

The problem is this line:

 IsChecked="{TemplateBinding Property=IsSelected}" 

It works great, but only in one direction. When you add an element to my SelectedPrivileges in the code, it will appear as checked, but when I check this element in the GUI, it will do nothing. (Without the CheckBox style, it works, so this is because TemplateBinding only works in one direction)

How do I make this work? At least I’m about something like a trigger, but I have no idea how to do this.

+4
source share
1 answer

I believe that what you are looking for is actually quite simple. You need to change the binding mode of the IsChecked property IsChecked as follows:

 {Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay} 

That should do it.

This and basically any other WPF binding tips can be found on this great cheat sheet .

+2
source

All Articles