取消选择具有扩展选择模式的WPF列表框

And*_*sen 5 c# wpf listbox

我有一个带扩展选择模式的简单列表框.选择工作几乎完全正常,就像它在资源管理器中工作.但取消选择并没有真正发挥作用.我想要的是当我点击列表框中元素范围之外的东西时,我希望取消选择所有元素.默认情况下,我似乎没有这样做,我做了一个涉及selectionchanged和mouseup的黑客攻击.但必须有更好的方法.有任何想法吗?

rmo*_*ore 3

添加取消选择功能并没有那么脏,而且您走在正确的轨道上。主要问题是,默认情况下,ListBox 内的 ListBoxItems 会一直延伸,因此很难不单击其中一个。

下面是一个 ListBox 示例,它修改了默认的 ItemContainerStyle,以便项目仅占据列表的左侧,并且项目之间也有一些间距。

<ListBox SelectionMode="Extended"
         Width="200" Mouse.MouseDown="ListBox_MouseDown">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="Background"
                    Value="LightBlue" />
            <Setter Property="Margin"
                    Value="2" />
            <Setter Property="Padding"
                    Value="2" />
            <Setter Property="Width"
                    Value="100" />
            <Setter Property="HorizontalAlignment"
                    Value="Left" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem >Item 1</ListBoxItem>
    <ListBoxItem >Item 2</ListBoxItem>
    <ListBoxItem >Item 3</ListBoxItem>
    <ListBoxItem >Item 4</ListBoxItem>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

要取消选择所选项目,我们只需在 EventHandler 中将 SelectedItem 设置为 null 即可。当我们单击 ListBoxItem 时,它将处理 MouseDown/Click 等来设置 SelectedItem 或修改 SelectedItems。因此,以及 RoutedEvents 的性质,我们只需在需要时处理 ListBox 中的 MouseDown 即可。当单击列表框内不属于项目一部分的某处时。

private void ListBox_MouseDown(object sender, MouseButtonEventArgs e)
{
    (sender as ListBox).SelectedItem = null;
}
Run Code Online (Sandbox Code Playgroud)