【发布时间】:2019-05-27 13:44:39
【问题描述】:
我有一个绑定到 Combobox 的集合,它的 SelectedItem 绑定到我的 viewmodel 属性 SelectedItem。
<ComboBox ItemsSource="{Binding itemSource}"
SelectedItem="{Binding SelectedItem}"/>
SelectedItem的类如下:
public class SelectedItem
{
public AnotherViewModel anotherViewModel {get;set;}
}
我使用了如下的用户控件:
<local:usercontrol DataContext="{Binding SelectedItem.anotherViewModel}"/>
我正在尝试在主视图中更改组合框的选择时更改用户控件的内容。
anotherViewModel 的属性更改仅在第一次反映到视图中。
在调试代码时,我发现anotherViewModel 的属性包含新值,但它没有反映到查看。
任何帮助将不胜感激。
编辑
Public class MainViewModel
{
public string property1 {get;set;} //has propertychanged implemented
public ObservableCollection<Item> Items {get;set;} //combobox itemsource
public Item SelectedItem {get;set;}//combobox selecteditem
}
public class Item
{
public AnotherViewModel anotherViewModel {get;set;}//has propertychanged implemented
}
public class AnotherViewModel
{
public string property1 {get;set;} //has propertychanged implemented
public string property2 {get;set;} //has propertychanged implemented
public ObservableCollection<string> items {get;set;} //has propertychanged implemented
}
<Window>
<Textbox Text="{Binding property1}"/>
<ComboBox ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"/>
<local:usercontrol DataContext="{Binding SelectedItem.anotherViewModel}"/>
<Window>
<UserControl>
<ListView ItemsSource="{Binding items}"/>
</UserControl>
【问题讨论】:
-
SelectedItem会引发PropertyChanged事件吗? -
是的。对不起,我忘了提。每个属性都实现了 INotifyPropertyChanged。 JFYI,在我创建一个新的用户控件并将公共代码移到它之前,它在单个视图中运行良好..
-
请提供更多详细信息。例如,
UserControl是如何定义的?还有SelectedItem属性?您是否将其设置为新的SelectedItem属性。 -
@mm8,这是一个设置了 DataContext 的简单 WPF 用户控件。我还没有实现任何依赖属性...
-
所以
UserControl是空的?当您选择一个项目时,您希望发生什么?
标签: c# wpf data-binding datacontext