Problem:
I have a Listbox, in that Listbox are Checkboxes. On the first click the Checkbox is selected and checked. On the second click the checkbox only gets set. One can reselect a different Checkbox using the arrow keys. My goal is, that the checkbox gets selected first and then checked afterwards (clicking again on it) thus removing the need for Arrow keys.
Goal:
The Code:
<ListBox Name="Terminals" ItemsSource="{Binding AllTerminals, Mode=OneWay}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Description}" Foreground="{Binding DisplayColor}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
this way the first click will only select ListBoxItem and checkboxes can be checked/unchecked by second click ListBox --ListBoxItem --CheckBox --ListBoxItem --CheckBox --ListBoxItem --CheckBox
Many people prefer to see checkboxes instead of the highlighting in a list box. There is a way to do this in XAML that does not require any change in ItemsSource, such as a property to bind to the IsChecked property of the Checkbox.
The TLDR is that you should add a CheckBox control to your DataTemplate and then bind the box's IsChecked property to the ListBoxItem.IsSelected property, using a relative source binding. In this file, we've got a ListBox that is bound to an Items property on the Window.
Therefore, when the ListViewItem that contains the CheckBox is selected, the CheckBox is checked. The following example shows how to create a column of CheckBox controls.
disable click registration on CheckBox via binding IsHitTestVisible
property to selection state of ListBoxItem:
<ListBox Name="Terminals" ItemsSource="{Binding AllTerminals, Mode=OneWay}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Description}"
IsHitTestVisible="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
Foreground="{Binding DisplayColor}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
this way the first click will only select ListBoxItem and checkboxes can be checked/unchecked by second click
after items are added to ListBox, the visual tree is the following:
ListBox
--ListBoxItem
--CheckBox
--ListBoxItem
--CheckBox
--ListBoxItem
--CheckBox
When user click on ListBoxItem, it gets selected (IsSelected=true). When user click on CheckBox, it gets checked or unchecked. But if IsHitTestVisible
set to false, click on element will not be registered. Since check/uncheck should work only for selected items, we can create binding between CheckBox.IsHitTestVisible and parent ListBoxItem.IsSelected to achieve such effect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With