【发布时间】:2018-03-18 19:28:51
【问题描述】:
我在使用 MVVM 的 UWP 中遇到问题,我有一个 Combobox 和一个 ItemsSource 绑定到我的 ViewModel 中的项目集合,并且在我的 VM 中还有一个来自该集合的项目 @987654323 @ 绑定到。
我需要在我的视图模型中随意更改项目来源和选定项目。问题是,如果SelectedItem 在任何时间点都不存在于ItemsSource 中,则SelectedItem 的绑定似乎会永久中断。
示例: 假设我有一个绑定到我的 VM 的 Comobox:
<ComoboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
现在在我的 ViewModel 中,我有:
public List<string> Items { get; set; } // Pretend these properties call on OnPropertyChanged
public string SelectedItem { get; set; }
public void Initialize() {
Items = new List<string> { "A", "B", "C", "D" };
SelectedItem = "B";
}
public void ChangeList() {
// This breaks the binding that the Combobox has with SelectedItem
Items = new List<string> { "E", "F", "G", "H" };
// This does nothing on the XAML side as the binding is already broken by this poing
SelectedItem = "H";
}
初始化时,应用程序将在选定的组合框中显示“B”。如果在代码中,比如说,我将其更改为“A”,那也将反映视图的变化。但是,当我调用 ChangeList() 时,组合框将设置为空白,并且将忽略我在后面的代码中所做的任何更改。
不幸的是,在我更新源列表之前将 SelectedItem 设置为 null 并不能解决我的问题。
我将如何更改 VM 中的源和选定项?
【问题讨论】:
-
同样的问题发生在 WPF 中。
-
基于侧边栏中的其他几个答案,我认为解决此问题的唯一方法是编写一个重新实现
SelectedItem的包装器对象(可能还有其他几个属性) .这感觉就像控件中的一个错误,它没有使用正确的方法来更新属性值。 (我开始走这条路,然后才发现我的问题是当列表被清除时空字符串会破坏绑定,但空字符串不会。)