WPF 取消选择 MVVM 中的 ListBox 项

WPF unselect ListBox item in MVVM

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

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

    ...

</ListBox>

我的 ViewModel class 具有以下属性:

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 项时,是否可以执行任何命令?该命令作为参数必须传递被点击项目的索引。如果有这样的可能性,只要你告诉我如何创建这个命令并将项目索引作为参数传递,对我来说就足够了。

您可以设置 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);
    }
}