不能用的SelectedItem = NULL明确列表框选择 - MVVM [英] Can't clear ListBox selection using SelectedItem = null - MVVM
问题描述
我有以下的数据模板(以及相应的视图模型,未显示):
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绑定到快照列表,在视图模型发现里面。我的目标是明确的SelectedItem,因此列表框回到其初始,未选中状态。该视图模型实现IPropertyNotified
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.
我说像这样的XAML绑定:
I added a binding in the XAML like so:
<ListBox SelectedItem={Binding SelectedSnapshot} .... />
在视图模型,我设置SelectedSnapshot = null,但什么也没有发生,即使RaisePropertyChanged被称为上属性。
In the view model, I set SelectedSnapshot = null, but nothing happens, even though RaisePropertyChanged was called on the property.
我再次SelectedIndex的,而不是尝试过的SelectedItem。仍然没有运气。
I tried again with SelectedIndex instead of SelectedItem. Still no luck.
我终于找到了解决方案,我将在下面详细信息。
I finally found the solution, which I will detail below.
推荐答案
忘记的SelectedItem和SelectedIndex的。答案就是的SelectedValue ,随着 IsSynchronizedWithCurrentItem =真。
Forget SelectedItem and SelectedIndex. The answer is SelectedValue, along with IsSynchronizedWithCurrentItem="True".
<ListBox IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding SelectedSnapshotValue}" .../>
然后,当我在视图模型调用ResetSelection(),SelectedSnapshotValue被设置为null,
Then, when I call ResetSelection() in the view model, SelectedSnapshotValue is set to null,
void ResetSelection()
{
SelectedSnapshotValue = null;
}
这将更新数据模板的绑定,使用绑定属性:
which updates the binding in the data template, using the bound property:
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.
这篇关于不能用的SelectedItem = NULL明确列表框选择 - MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!