【问题标题】:WPF ListBox with CheckBoxes: select the checkbox before checking itWPF ListBox with CheckBoxes:选中复选框之前选中它
【发布时间】:2017-03-01 08:04:21
【问题描述】:

问题

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

目标

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

守则

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

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

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

    <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 并且可以通过第二次点击来选中/取消选中复选框


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

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

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

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 2019-03-12
      • 1970-01-01
      • 2022-01-21
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多