gpt4 book ai didi

WPF:根据相应的ViewModel(MVVM)切换UserControls

转载 作者:行者123 更新时间:2023-12-02 05:30:04 29 4
gpt4 key购买 nike

我将尝试通过想象这个例子来简化我正在处理的任务:

假设我们有以下模型类层次结构:

Animal
Lion
Snake
Bird

...对应的ViewModel:

AnimalCollectionViewModel
AnimalViewModel
LionViewModel
SnakeViewModel
BirdViewModel

...以及相应的 View :

AnimalCollectionView
LionView
SnakeView
BirdView

假设 AnimalCollection 包含一个充满不同类型动物的对象的列表,并且在列表下方有一个属性网格,用于设置所选动物的属性。显然,属性网格将具有不同的属性,并且当所选项目的类型发生变化时应该发生变化。

问题是:如何按照MVVM模式实现WPF中属性网格的切换?使用什么机制?

目前,我在基本 ViewModel (AnimalViewModel.PropertyGridType = {Lion, Snake, Bird}) 中有一个抽象枚举属性,派生类通过返回相应的值来实现该属性。 AnimalCollectionView 根据此属性的值更改属性网格用户控件。像这样的事情:

...

<UserControl.Resources>
<Style x:Key="PropertyGridStyle" TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding PropertyGridType}" Value="Lion">
<Setter Property="Content">
<Setter.Value>
<view:LionPropertyGridView />
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding PropertyGridType}" Value="Snake">
<Setter Property="Content">
<Setter.Value>
<view:SnakePropertyGridView />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>

<ContentControl Style="{StaticResource PropertyGridStyle}" />

...

但我不确定这是否是正确的方法。 (至少我不喜欢引入辅助枚举属性。是否可以根据 ViewModel 类型推导必要的用户控件?)有人可以建议其他选择吗?提前致谢!

最佳答案

Is it possible to deduce the necessary user control based on a ViewModel type?

你的意思是,像这样?

<Window.Resources>
<DataTemplate DataType="{x:Type vm:LionViewModel}">
<v:LionView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SnakeViewModel}">
<v:SnakeView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:BirdViewModel}">
<v:BirdView/>
</DataTemplate>
</Window.Resources>

请参阅 Josh Smith's article on MVVM 中的“将 View 应用于 View 模型” .

编辑:

这是一个基于类型的模板选择的简单示例,您可以将其粘贴到 Kaxaml 中以向自己证明它确实有效:

<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Page.Resources>
<sys:String x:Key="string">this is a string</sys:String>
<sys:Int32 x:Key="int32">1234</sys:Int32>
<DataTemplate DataType="{x:Type sys:String}">
<TextBlock Foreground="Red" Text="{Binding}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type sys:Int32}">
<TextBlock Foreground="Blue" Text="{Binding}"/>
</DataTemplate>
</Page.Resources>
<StackPanel>
<ContentControl Content="{Binding Source={StaticResource string}}"/>
<ContentControl Content="{Binding Source={StaticResource int32}}"/>
</StackPanel>
</Page>

关于WPF:根据相应的ViewModel(MVVM)切换UserControls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5018613/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com