gpt4 book ai didi

wpf - 在 XAML 中关联 View 和 ViewModel 对,无需重复代码

转载 作者:行者123 更新时间:2023-12-01 12:45:37 27 4
gpt4 key购买 nike

我已阅读 a very nice tutorial关于让 ViewModels 做他们的事情,而 View 只是通过数据绑定(bind)与 DataTemplates 自行切换。

我成功创建了一个具有 ApplicationViewModel 的窗口,而该窗口又具有硬编码的 DummyViewModel 作为其 CurrentScreen 属性

<Window x:Class="MyProject.Aplication"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:MyProject.ViewModels"
xmlns:v="clr-namespace:MyProject.Views"
xmlns:System="clr-namespace:System;assembly=mscorlib"
Title="Killer Application" Height="900" Width="1440"
WindowState="Maximized">

<!-- This view has its viewmodel as data context, which has a CurrentScreen property -->
<Window.DataContext>
<vm:AplicationViewModel/>
</Window.DataContext>

<Window.Resources>
<!-- each ViewModel will explicitly map to its current View - while this should happen EXPLICITLY, no? -->
<DataTemplate DataType="{x:Type vm:DummyViewModel}">
<v:DummyView/>
</DataTemplate>
<!-- Doc, are you telling me I'll have to fill this up for EVERY VIEW/VIEWMODEL? -->
<DataTemplate DataType="{x:Type vm:YetAnotherViewModel}">
<v:YetAnotherView/>
</DataTemplate>
</Window.Resources>

<!-- the content is bound to CurrentScreen property of the data context -->
<ContentControl Content="{Binding CurrentScreen}" />
</Window>

我想有一些(非常简单和直接,如果可能的话)方法来获得相同的结果,而不必为窗口可以显示的每个可能的屏幕详尽地编写一个 DataTemplate 窗口资源。有办法吗?

最佳答案

If you're doing MVVM, then you should be using an MVVM framework .例如,Caliburn.Micro将根据约定进行 View 定位和自动绑定(bind)。

关于wpf - 在 XAML 中关联 View 和 ViewModel 对,无需重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16286278/

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