WPF MVVM的ItemsControl与根据对象类型多的ViewModels [英] WPF MVVM ItemsControl with Multiple ViewModels depending on the object type

查看:286
本文介绍了WPF MVVM的ItemsControl与根据对象类型多的ViewModels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个类型都来自相同的接口继承项目的集合。这势必给一个ItemsControl。窗口的DataContext设置为保存集合视图模型。



我想什么做的是有不同类型的集合中的每个项目使用不同的视图模型。



所以,如果我ItemsControl中的模板的设置像下面我想有第一个模板有ViewModel1的一个DataContext,第二有ViewModel2的一个DataContext。我不能直接设置对他们的DataContext的,因为ItemsControl的将设置的DataContext的项目。



任何人都知道解决这个,或者更好的方式来做到这一点使用MVVM?

 <数据类型的DataTemplate ={X:类模型:ItemType1}> 
<控制:MyControl文本={结合体}/>
< / DataTemplate中>

<数据类型的DataTemplate ={X:类模型:ItemType2}>
<控制:MyControl2文本={结合体}/>
< / DataTemplate中>


解决方案

为什么你不只是暴露的ViewModels的集合?

  VAR的ViewModels =新的ObservableCollection< ViewModelBase>(items.Select(CreateViewModelFromItem)); 


私人ViewModelBase CreateViewModelFromItem(项目项)
{
如果(产品ItemType1)返回新ViewModel1((ItemType1)项);
如果(产品ItemType2)返回新ViewModel2((ItemType2)项);
...
抛出新的ArgumentException(未知型号类型);
}

和改变你的DataTemplates绑定到的ViewModels,而不是项目...


I have a collection that holds multiple types of items that all inherit from the same interface. This is bound to an ItemsControl. The DataContext of the window is set to the ViewModel that holds the collection.

What I would like to do is have each item of a different type in the collection use a different ViewModel.

So if my templates in the itemscontrol are setup like below I would like to have the first template have a DataContext of ViewModel1 and the second have a DataContext of ViewModel2. I can't set the DataContext directly on them because the ItemsControl will set the DataContext to the item.

Anyone know a solution to this, or a better way to do it using MVVM?

<DataTemplate DataType="{x:Type Models:ItemType1}">
    <Controls:MyControl Text="{Binding Body}"/>
</DataTemplate>

<DataTemplate DataType="{x:Type Models:ItemType2}">
    <Controls:MyControl2 Text="{Binding Body}"/>
</DataTemplate>

解决方案

Why don't you just expose a collection of ViewModels ?

var viewModels = new ObservableCollection<ViewModelBase>(items.Select(CreateViewModelFromItem));


private ViewModelBase CreateViewModelFromItem(Item item)
{
    if (item is ItemType1) return new ViewModel1((ItemType1)item);
    if (item is ItemType2) return new ViewModel2((ItemType2)item);
    ...
    throw new ArgumentException("Unknown model type");
}

And change your datatemplates to bind to the viewmodels, not the items...

这篇关于WPF MVVM的ItemsControl与根据对象类型多的ViewModels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆