c# - 通过单击背景在 ListBox 中选择一个 CheckBox

标签 c# wpf xaml checkbox listbox

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

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

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

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

编辑:似乎没有属性可以解决这个问题。
那么我该怎么做才能用 OnMouseLeftButtonDown 来处理这个问题。
左键选择的项目必须勾选..

最佳答案

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

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

*编辑

可以绑定(bind)IsCheckedIsSelected祖先 ListBoxItem 的属性。

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

或者您可以使用 IValueConverter具有更大的灵 active 并传入像 SelectedIndex 这样的标识符列表的 + a 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并根据需要进行修改。

关于c# - 通过单击背景在 ListBox 中选择一个 CheckBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28244649/

相关文章:

.net - AutomationProperties.Name VS x :Name

c++ - 从 QT 中的主窗口发出信号

xaml - Xamarin.Forms "databind"Xaml 中的单个值 <x :Array type ="{x:Type x:String}">

xaml - ContentDialog 的大小不适合具有大 TextBlock 的通用应用程序中的内容

c# - isMouseOver 在带有路径的 Canvas 中

c# - 安全解析字符串的最佳做法是什么?

c# - 在 Realm 中使用特定于项目的 ViewModel 的最佳方式是什么?

c# - 当T本身是类型时,为什么必须使用typeof(T)来获得Type?

c# - 使用 MVVM 在 WPF 中连续显示当前时间显示

c# - XAML 分组的 GridView/语义缩放不显示所有子项?