我正在使用 MVVM 模式在 WPF 中开发一个应用程序,并且遇到了一些可能有点独特的东西。
我有一个抽象类 MapEntity
它表示可以显示在我的应用程序的绘图表面上的实体。其他类如 LineEntity
, TextEntity
等等,继承自MapEntity
.
为了显示这些,我创建了一个 ObservableCollection
对于每种类型并将其绑定(bind)到我的 XAML,它采用每个实体的属性并显示它们。 (例如,创建一个颜色和文本为 TextEntity
的文本框)
一起管理这些实体感觉有点像黑客。如果每个实体都有一堆集合,我可以创建一个 ObservableCollection<MapEntity>
,并将所有实体添加到其中。这将使处理它们更容易,例如在用户拖动实体时检查它们的边界,或通过 MapEntity
中定义的更新方法更新它们。 .标准继承内容。
当使用这种技术时问题来了,有没有办法创建一个 ItemsControl
绑定(bind)到此单个集合(而不是将每个 ItemsControl
绑定(bind)到 TextEntity
、LineEntity
等的集合),但只显示特定类型的元素?
例如:
View 模型:
public ObvervableCollection<MapEntity> Entities { get; set; //OnPropertyChanged stuff}
...
Entities.Add(new LineEntity(...));
Entities.Add(new TextEntity(...));
所以,我添加了不同的 MapEntities
到单个集合而不是每个类型的多个集合。
查看:
使用单独的集合,我可以绑定(bind)每个 ItemsControl
项目到特定集合,但使用一个 Entities
集合,我找不到一种方法来“过滤”从 MapEntity
派生的某种类型的元素.
所以不要这样做:
<ItemsControl ItemsSource="{Binding LineEntities}"> <!-- More Stuff --> </ItemsControl>
<ItemsControl ItemsSource="{Binding TextEntities}"> <!-- More Stuff --> </ItemsControl>
我想做的事:
<ItemsControl ItemsSource="{Binding Entities WHERE type = LineEntity}"> <!-- More Stuff --> </ItemsControl>
<ItemsControl ItemsSource="{Binding Entities WHERE type = TextEntity}"> <!-- More Stuff --> </ItemsControl>
(显然无效),但基本上我只想从集合中“过滤”出所需的类型,通过没有单独的集合,可以更轻松地在 ViewModel 中进行管理。 (因此必须对每个单独运行操作)
我相当确定这是不可能的,但我想如果有人有任何想法,我会通过 XAML 或 ViewModel 询问。
最佳答案
您可能已经知道,ItemsControl
会根据每个项目的类型自动选择正确的 ItemTemplate
。
为从 MapEntity 派生的每个类型定义一个空的 DataTemplate,如下所示,以便任何 ItemsControl
(未明确设置其 ItemTemplate)从这些资源中进行选择。
<Window.Resources>
<DataTemplate DataType="{x:Type vm:TextEntity}">
</DataTemplate>
<DataTemplate DataType="{x:Type vm:LineEntity}">
</DataTemplate>
</Window.Resources>
现在您需要为每个 ItemsControl 覆盖其中一个。
<ItemsControl ItemsSource="{Binding Entities}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type vm:TextEntity}">
<!-- Template for text entity -->
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
关于c# - DataBind到ObservableCollection,只显示某个派生类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28385287/