在ViewModel中创建视图对象

Ram*_*esh 2 c# wpf mvvm commandbinding

我在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)
                {
Run Code Online (Sandbox Code Playgroud)

但我开始知道,从MVM模式中调用viewmodel的窗口是错误的.

也在下面的链接中说明.

MV-VM设计问题.从ViewModel调用View

请提供替代解决方案,帮助我任何人.

提前致谢.

She*_*dan 7

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

DataContext = this;
Run Code Online (Sandbox Code Playgroud)

在这个例子中,'视图模型'实际上是MainWindow'视图' 背后的代码......但是视图和视图模型被捆绑在一起,这是我们试图通过使用MVVM避免的.

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

<DataTemplate DataType="{x:Type ViewModels:YourViewModel}">
    <Views:YourView />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

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

<ContentControl Content="{Binding ViewModel}" />
Run Code Online (Sandbox Code Playgroud)

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

<Window.Resources>
    <ViewModels:YourViewModel x:Key="ViewModel" />
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样引用它:

<ContentControl Content="{Binding Source={StaticResource ViewModel}}" />
Run Code Online (Sandbox Code Playgroud)