wpf 无法使用 SelectedItem = null 清除列表框选择 - MVVM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16429392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't clear ListBox selection using SelectedItem = null - MVVM
提问by NielW
I have the following data template (and a corresponding view model, not shown):
我有以下数据模板(和相应的视图模型,未显示):
<DataTemplate DataType="{x:Type logic:SnapshotListViewModel}">
<ListBox ItemsSource="{Binding Snapshots}" />
</DataTemplate>
ItemsSource is bound to a list of Snapshots, found inside the viewmodel. My goal is to clear the SelectedItem, so the listbox goes back to its initial, unselected state. The view model implements IPropertyNotified.
ItemsSource 绑定到视图模型中的快照列表。我的目标是清除 SelectedItem,以便列表框恢复到其初始的未选中状态。视图模型实现了 IPropertyNotified。
I added a binding in the XAML like so:
我在 XAML 中添加了一个绑定,如下所示:
<ListBox SelectedItem={Binding SelectedSnapshot} .... />
In the view model, I set SelectedSnapshot = null, but nothing happens, even though RaisePropertyChanged was called on the property.
在视图模型中,我设置了 SelectedSnapshot = null,但没有任何反应,即使在该属性上调用了 RaisePropertyChanged。
I tried again with SelectedIndex instead of SelectedItem. Still no luck.
我再次尝试使用 SelectedIndex 而不是 SelectedItem。仍然没有运气。
I finally found the solution, which I will detail below.
我终于找到了解决方案,我将在下面详细介绍。
回答by NielW
Forget SelectedItem and SelectedIndex. The answer is SelectedValue, along with IsSynchronizedWithCurrentItem="True".
忘记 SelectedItem 和 SelectedIndex。答案是SelectedValue以及IsSynchronizedWithCurrentItem="True"。
<ListBox IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding SelectedSnapshotValue}" .../>
Then, when I call ResetSelection() in the view model, SelectedSnapshotValue is set to null,
然后,当我在视图模型中调用 ResetSelection() 时,SelectedSnapshotValue 设置为 null,
void ResetSelection()
{
SelectedSnapshotValue = null;
}
which updates the binding in the data template, using the bound property:
它使用 bound 属性更新数据模板中的绑定:
private SnapshotViewModel selectedSnapshotValue;
public SnapshotViewModel SelectedSnapshotValue
{
get { return selectedSnapshotValue; }
set
{
if (selectedSnapshotValue != value)
{
selectedSnapshotValue = value;
RaisePropertyChanged("SelectedSnapshotValue");
}
}
}
This is the only way I was able to get my listbox to reset the selection.
这是我能够让我的列表框重置选择的唯一方法。

