【发布时间】:2013-04-26 14:40:08
【问题描述】:
我正在尝试动态更改在ObservableCollection 中定义的UserControl 视图。
public class MItem : INotifyPropertyChanged
{
private UserControl _mView;
public UserControl MView
{
get { return _mView; }
set
{
if (_mView != value)
{
_mView = value;
OnPropertyChanged("MView");
}
}
}
...
}
在单独的视图中我有:
ObservableCollection<MItem> _items = new ObservableCollection<MItem>;
_items.Add(new MItem{MView = MyView});
显然,在创建该视图的新对象然后将其分配给 Grid 上的子对象时会出现问题 - 它会给我一个类型错误。
我尝试过类似的方法:
_items[0].MView = new UserControl(); // I know this wouldn't work
我的主要问题是,有没有人尝试过实现类似的东西,你是如何解决的?
谢谢
【问题讨论】:
-
这与 MVVM 所代表的一切背道而驰。您不应该在
ObservableCollection中引用任何 UI 元素。而是创建一个ObservableCollection<SomeViewModel>,然后使用正确的DataTemplates在屏幕上呈现这些。
标签: c# wpf view observablecollection