WPF DataTemplate / DataTemplateSelector —由2个不同的View使用的ViewModel的最佳方法?
|
基本上,我有以下情形:
ViewModel:
FooViewModel : BaseViewModel
,BarViewModel : BaseViewModel
浏览次数:MainView
,FooView
,BarView
现在,我“注入”视图并使用DataTemplate
和DataTemplateSelector
设置DataContext
。显然,我的ItemsControl
ItemSource
绑定到ObservableCollection<BaseViewModel>
,其中包含(现在)实例FooViewModel
和BarViewModel
问题是我想介绍一个我想使用相同的ѭ11的ѭ13。我想我将创建另一个DataTemplate
并让我的DataTemplateSelector
返回它,但是需要有特殊的逻辑来确定要返回的DataTemplate(我不能只是通过那里的ViewModel),这意味着我在BaseViewModel中必须具有某种类型的属性或字段。我不知道这是否真的是个好主意,因为这似乎是将字段/属性引入到仅用于选择视图的ViewModel中。这不会影响我的单元测试,但是包含一个字段只是为了帮助决定选择哪个UI视图似乎是一种浪费。我不认为这会破坏MVVM,但是我很好奇是否有人还有其他更好的主意吗?我不喜欢的替代想法甚至更多...
想法2:
-将FooViewModel转换为2个不同的FooViewModel扩展的基类(即BaseFooViewModel,FooViewModel,DifferentFooViewModel)。这似乎很愚蠢,因为除了FooViewModel和DifferentFooViewModel的类类型外,它们之间确实没有任何区别。
想法3:
-只需复制FooViewModel并将其制成FooViewModel2(它将与FooViewModel完全相同)。这似乎比想法2更糟。
样本代码(明显调整):
public abstract class BaseViewModel : NotificationObject
{
//Common Stuff
}
public abstract MainViewModel : NotificationObject
{
public MainViewModel()
{
MyItems = new ObservableCollection<BaseViewModel>()
{
new FooViewModel();
new BarViewModel();
new FooViewModel(); //New Item -- I want it to use the DifferentFooView
}
//Load items from a DAL later
}
public ObservableCollection<BaseViewModel> MyItems { get; set; }
//Other Stuff
}
<l:MyItemsControl ItemSource={Binding MyItems} ContentTemplateSelector={StaticResource MyTemplateSelector} />
谢谢!
没有找到相关结果
已邀请:
1 个回复
涸坍饺