【问题标题】:Select a CheckBox in a ListBox by clicking on the background通过单击背景在 ListBox 中选择一个 CheckBox
【发布时间】:2015-03-30 10:41:58
【问题描述】:

我的ListBox有点问题
我可以通过单击文本来查看CheckBox
但是如果我点击背景,我就无法查看我的CheckBox
这让我感觉很糟糕......

我想我可以创建一种方法来解决我的问题,
但我想知道是否有属性可以轻松解决此问题。
感谢您的帮助。

<ListBox x:Name="DeleteEntreesListBox">
    <CheckBox x:Name="myTextBox" Content="Hello"/>
</ListBox>

如果我的光标在文本上,则该框是灰色的,可以检查。 Screen
如果我的光标不在文本上而是在背景上,则该框为白色且无法检查Screen

编辑:似乎没有属性可以解决这个问题。
那么我该如何处理这个问题,例如OnMouseLeftButtonDown
左键选中的项目必须设置复选框为check..

【问题讨论】:

  • 您是在谈论列表框项目何时更改吗? SelectedIndexChanged 应该有一个事件。您可以在该事件上将所选项目转换为复选框,然后将选中 = true。还是你的意思是别的?
  • 当您的光标位于 ListBox.Item 上时(背景蓝色:已选中),我希望能够单击此蓝色区域中的任意位置以选中我的框。实际上,我必须点击文本才能做到这一点..
  • 因此单击“蓝色背景”应该会更改列表框选定项。你试过that event吗?
  • 只需将复选框的ischecked绑定到项目的isselected
  • @MethodMan :我正在处理 ListBox,而不是 ListView

标签: c# wpf xaml checkbox listbox


【解决方案1】:

尝试将宽度设置为与列表框(或任何其他父级)相同

<ListBox x:Name="DeleteEntreesListBox">
    <CheckBox x:Name="myTextBox" Content="Hello" Width="{Binding ActualWidth,ElementName=DeleteEntreesListBox}"/>
</ListBox>

*编辑

您可以将IsChecked 绑定到祖先ListBoxItem 的IsSelected 属性。

<CheckBox x:Name="myTextBox2" Content="Hello" 
          IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, 
          AncestorType={x:Type ListBoxItem}}, 
          Path=IsSelected}"/>

或者您可以更灵活地使用IValueConverter,并传入一个标识符,如列表中的SelectedIndex + 一个ConverterParameter 和一个匹配的int,如果它们匹配(或任何其他),则转换为true标识符)。

<ListBox x:Name="DeleteEntreesListBox">
    <CheckBox x:Name="myTextBox1" Content="Hello">
        <CheckBox.IsChecked>
            <Binding Path="SelectedIndex" ElementName="DeleteEntreesListBox" Converter="{StaticResource IndexToBoolConverter}">
                <Binding.ConverterParameter>
                    <sys:Int32>0</sys:Int32>
                </Binding.ConverterParameter>
            </Binding>
        </CheckBox.IsChecked>
    </CheckBox>
</ListBox>

请注意,您需要在 xaml 中引用它才能将 int 作为参数传递:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

转换器可以是这样的:

class IndexToBoolConverter : IValueConverter
{
    #region IValueConverter Members

    object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
            if (parameter != null && (int)value == (int)parameter)
            {
                return true;
            }
            else
                return false;
    }

    object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool)value == true)
            return false;
        else
            return true;
    }

    #endregion
}

虽然我认为您应该创建一个不错的自己的 UserControl 继承自 ListBox 并根据需要对其进行修改。

【讨论】:

  • 不错的尝试,但我需要保持这个宽度。
  • 谢谢你的回答老兄!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
相关资源
最近更新 更多