带复选框的 WPF 列表框:选中复选框之前选中它 [英] WPF ListBox with CheckBoxes: select the checkbox before checking it

查看:42
本文介绍了带复选框的 WPF 列表框:选中复选框之前选中它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我有一个列表框,其中的列表框是复选框.在第一次单击时,复选框被选中并被选中.在第二次单击时,复选框只会被设置.可以使用箭头键重新选择不同的复选框.我的目标是,先选中复选框,然后再检查(再次单击它),从而消除对箭头键的需要.

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.

目标:

  • 第一次点击时选择项目
  • 在第二次点击时选中复选框

代码:

<ListBox Name="Terminals" ItemsSource="{Binding AllTerminals, Mode=OneWay}" IsSynchronizedWithCurrentItem="True">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Description}" Foreground="{Binding DisplayColor}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

推荐答案

通过将 IsHitTestVisible 属性绑定到 ListBoxItem 的选择状态来禁用 CheckBox 上的点击注册:

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>

这样第一次点击只会选择ListBoxItem,第二次点击可以选中/取消选中复选框

this way the first click will only select ListBoxItem and checkboxes can be checked/unchecked by second click

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

after items are added to ListBox, the visual tree is the following:

ListBox
 --ListBoxItem
   --CheckBox
 --ListBoxItem
   --CheckBox
 --ListBoxItem
   --CheckBox

当用户单击 ListBoxItem 时,它会被选中 (IsSelected=true).当用户单击 CheckBox 时,它会被选中或取消选中.但是如果 IsHitTestVisible 设置为 false,点击元素将不会被注册.由于选中/取消选中应该只对选中的项目起作用,我们可以在 CheckBox.IsHitTestVisible 和父 ListBoxItem.IsSelected 之间创建绑定来达到这样的效果

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

这篇关于带复选框的 WPF 列表框:选中复选框之前选中它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆