c# - 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
单击该项目时我都可以执行任何命令吗?该命令作为参数必须传递被点击项目的索引。如果有这样的可能性,只要您向我展示如何创建此命令并将项目索引作为参数传递,这对我来说就足够了。
解决方案
您可以设置 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);
}
}
推荐阅读
- ios - 快速按钮单击以显示带有工具栏视图的键盘
- typescript - 如何使用带有 Typescript 的 expo AppLoading 组件?
- javascript - 使用整数数组参数的排序函数不起作用
- sql - 查找所有开头包含“+7”的数字
- java - 无法检测到 NoMoreReturnsException 的来源
- python - cx_Freeze 不想将图标应用于 .exe 文件
- google-sheets - 查找值并将它们添加到动态工作表中的表中
- wordpress - 用户(图像)上的 WP ACF 字段不时消失
- list - 如果 Flutter 中的网格列表为空,则插入 Text()
- javascript - 两个复制文本按钮?