首页 > 解决方案 > WPF取消选择MVVM中的ListBox项目

问题描述

我添加ListBox到我的 XAML 文件中,如下所示:

<ListBox
    SelectedIndex="{Binding SelectedIndex}"
    ItemsSource="{Binding  Answers}">

    ...

</ListBox>

我的 ViewModel 类具有以下属性:

private int? selectedIndex;
public int? SelectedIndex
{
    get => selectedIndex;
    set
    {
        selectedIndex = value;
        RaisePropertyChanged(nameof(SelectedIndex));
    }
}

private ObservableCollection<string> answers;
public ObservableCollection<string> Answers
{
    get => answers;
    private set
    {
        answers = value;
        RaisePropertyChanged(nameof(Answers));
    }
}

现在,当我单击已选择的项目时,我想取消选择该项目(所以我认为SelectedIndex = null会完成这项工作)。我该怎么做?我试图找到一个解决方案,但没有任何成功。

每次ListBox单击该项目时我都可以执行任何命令吗?该命令作为参数必须传递被点击项目的索引。如果有这样的可能性,只要您向我展示如何创建此命令并将项目索引作为参数传递,这对我来说就足够了。

标签: c#wpfmvvmlistbox

解决方案


您可以设置 PreviewMouseLeftButtonDown (或类似的)事件处理程序

<ListBox ...>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown"
                         Handler="ListBoxItemPreviewMouseLeftButtonDown"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

就是这样做的:

private void ListBoxItemPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (sender is ListBoxItem listBoxItem && listBoxItem.IsSelected)
    {
        listBoxItem.Dispatcher.InvokeAsync(() => listBoxItem.IsSelected = false);
    }
}

推荐阅读