在具有Extended SelectionMode的ListBox中单击取消选择

时间:2017-02-22 13:31:38

标签: c# wpf listbox selection

我有ListBox SelectionMode="Extended"。您只能在单击时按住 ctrl 取消选择最后一项。我希望能够通过点击它来取消选择该项目,同时不更改Extended选择模式的行为。

我只找到关于此主题的one question,它实际上有不同的目标(能够通过点击ListBox外部来取消选择所有项目。)

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的要求,您可以处理PreviewMouseLeftButtonDown容器的ListBoxItem事件,如果已经选择它,则取消选择它:

<ListBox SelectionMode="Extended">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="OnMouseLeftButtonDown"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBoxItem>1</ListBoxItem>
    <ListBoxItem>2</ListBoxItem>
    <ListBoxItem>3</ListBoxItem>
</ListBox>
private void OnMouseLeftButtonDown(object sender, MouseEventArgs e)
{
    ListBoxItem lbi = sender as ListBoxItem;
    if (lbi != null)
    {
        if (lbi.IsSelected)
        {
            lbi.IsSelected = false;
            e.Handled = true;
        }
    }
}

这样您就可以在不使用CTRL键的情况下取消选择项目。

相关问题