Squirrel in training
Squirrel in training

Reputation: 788

WPF ListBox with CheckBoxes: select the checkbox before checking it

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>

Upvotes: 5

Views: 1932

Answers (1)

ASh
ASh

Reputation: 35681

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

Upvotes: 7

Related Questions