gpt4 book ai didi

c# - 无法使用 SelectedItem = null - MVVM 清除 ListBox 选择

转载 作者:太空狗 更新时间:2023-10-29 20:58:55 25 4
gpt4 key购买 nike

我有以下数据模板(和相应的 View 模型,未显示):

<DataTemplate DataType="{x:Type logic:SnapshotListViewModel}">
<ListBox ItemsSource="{Binding Snapshots}" />
</DataTemplate>

ItemsSource 绑定(bind)到 View 模型中的快照列表。我的目标是清除 SelectedItem,以便列表框返回到其初始的未选中状态。 View 模型实现 IPropertyNotified。

我在 XAML 中添加了一个绑定(bind),如下所示:

<ListBox SelectedItem={Binding SelectedSnapshot} .... />

在 View 模型中,我设置了 SelectedSnapshot = null,但没有任何反应,即使在属性上调用了 RaisePropertyChanged。

我再次尝试使用 SelectedIndex 而不是 SelectedItem。仍然没有运气。

我终于找到了解决方案,我将在下面详细介绍。

最佳答案

忘掉 SelectedItem 和 SelectedIndex。答案是 SelectedValue,以及 IsSynchronizedWithCurrentItem="True"。

<ListBox IsSynchronizedWithCurrentItem="True" 
SelectedValue="{Binding SelectedSnapshotValue}" .../>

然后,当我在 View 模型中调用 ResetSelection() 时,SelectedSnapshotValue 设置为 null,

void ResetSelection()
{
SelectedSnapshotValue = null;
}

使用绑定(bind)属性更新数据模板中的绑定(bind):

    private SnapshotViewModel selectedSnapshotValue;
public SnapshotViewModel SelectedSnapshotValue
{
get { return selectedSnapshotValue; }
set
{
if (selectedSnapshotValue != value)
{
selectedSnapshotValue = value;
RaisePropertyChanged("SelectedSnapshotValue");
}
}
}

这是我能够让我的列表框重置选择的唯一方法。

关于c# - 无法使用 SelectedItem = null - MVVM 清除 ListBox 选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16429392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com