在ViewModel中创建视图对象

本文关键字:视图 对象 创建 ViewModel | 更新日期: 2023-09-27 18:27:31

我的C#WPF MVVM应用程序中有以下代码。

public RelayCommand PolishCommand
    {
        get
        {
            polishcommand = new RelayCommand(e =>
            {
                PolishedWeightCalculatorViewModel model = new PolishedWeightCalculatorViewModel(outcomeIndex, OutcomeSelectedItem.RoughCarats);
                PolishedWeightCalculatorView polish = new PolishedWeightCalculatorView(model);
                bool? result = polish.ShowDialog();
                if (result.HasValue)
                {

但我发现,在MVVM模式中,从视图模型调用窗口是错误的。

也在下面的链接中说明。

M-V-VM设计问题。从ViewModel 调用视图

请通过提供替代解决方案来帮助我。

提前谢谢。

在ViewModel中创建视图对象

您是对的,通常您应该永远不要访问视图模型中的视图。相反,在WPF中,我们将视图的DataContext属性设置为相关视图模型的实例。有很多方法可以做到这一点。最简单但最不正确的是创建一个新的WPF项目,并将其放入MainWindow.xaml.cs:的构造函数中

DataContext = this;

在这种情况下,"视图模型"实际上是MainWindow"视图"的代码。。。但是视图和视图模型被绑定在一起,这是我们试图通过使用MVVM来避免的。

更好的方法是在Resources部分的DataTemplate中设置关系(我更喜欢在App.xaml:中使用App.Resources

<DataTemplate DataType="{x:Type ViewModels:YourViewModel}">
    <Views:YourView />
</DataTemplate>

现在,无论您在UI中"显示"视图模型,相关视图都将自动显示。

<ContentControl Content="{Binding ViewModel}" />

第三种方法是在Resources部分中创建视图模型的实例,如下所示:

<Window.Resources>
    <ViewModels:YourViewModel x:Key="ViewModel" />
</Window.Resources>

然后你可以这样称呼它:

<ContentControl Content="{Binding Source={StaticResource ViewModel}}" />

我之前回答过一个非常类似的问题,该问题详细说明了如何从视图模型中打开一个新窗口,同时保持MVVM模式所提倡的关注点分离。我希望这能有所帮助:在MVVM 中打开一个新窗口

您可以违反规则。您不必完全遵循MVVM。我总是使用命令来创建新视图。你甚至可以创建一个事件(Amagosh,他刚才说了吗!?),当你点击一个按钮时。我的意思是,这只是我的观点,我想这取决于你喜欢的编程风格。