带有Checkbox的XAML列表框,选中复选框bevor检查它

Squ*_*ing 4 wpf xaml

问题:
我有一个Listbox,Listbox是Checkboxes.在第一次单击时,选中并选中复选框.在第二次单击时,仅设置复选框.可以使用箭头键重新选择不同的复选框.我的目标是,首先选中复选框,然后再检查(再次单击它),从而无需使用箭头键.

目标:

  • 首次单击时选择项目
  • 第二次单击检查复选框

守则:

<ListBox Name="Terminals" ItemsSource="{Binding AllTerminals, Mode=OneWay}" IsSynchronizedWithCurrentItem="True">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Description}" Foreground="{Binding DisplayColor}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

ASh*_*ASh 6

禁用CheckBox上的点击注册,通过绑定IsHitTestVisible属性到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>
Run Code Online (Sandbox Code Playgroud)

这样,第一次单击将只选择ListBoxItem,并且可以通过第二次单击来选中/取消选中复选框


将项目添加到ListBox后,可视化树如下:

ListBox
 --ListBoxItem
   --CheckBox
 --ListBoxItem
   --CheckBox
 --ListBoxItem
   --CheckBox
Run Code Online (Sandbox Code Playgroud)

当用户单击ListBoxItem时,它将被选中(IsSelected = true).当用户单击CheckBox时,它将被选中或取消选中.但是如果IsHitTestVisible设置为false,则不会注册click元素.由于check/uncheck仅适用于所选项目,因此我们可以在CheckBox.IsHitTestVisible和父ListBoxItem.IsSelected之间创建绑定以实现此类效果