WPF/MVVM Windows服务,无需重置视图模型 [英] WPF/MVVM windowsservice without viewmodel reset

查看:77
本文介绍了WPF/MVVM Windows服务,无需重置视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从视图模型的视图创建中删除

I'm want to remove from my view model's creating of view's

我写了WinodwsService类来创建一个新窗口:

I wrote WinodwsService class to creating a new window:

public class WindowService : IWindowService
{
    public void ShowWindow(object viewModel)
    {
        //var win = new DXWindowCloasable(viewModel);
        var win = new DXWindow();
        win.Content = viewModel;
        win.DataContext = viewModel;
        win.ShowDialog();

    }
}

在视图模型中,我调用方法:

In view model I call method:

var vm = new PolaPrzewoznikowViewModel(konf);
IWindowService wnf = new WindowService(); // this is only for test
wnf.ShowWindow(vm);

在UserControl中,我定义了视图模型类型:

In UserControl I have defined view model type:

<UserControl.DataContext>
    <local:PolaPrzewoznikowViewModel />
</UserControl.DataContext>

有了这个,我可以在命令上钻取(CTRL + B),并在投影视图时使用代码补全-这非常有帮助.

When I have this, I can drill down (CTRL + B) on commands, and user an code completition when I'm projecting a View - this is very helpful.

但是...当我使用 win.ShowDialog();创建新的视图模型.并且显示的视图具有不带参数的视图模型(默认构造函数).

But... when I use win.ShowDialog(); the new view model is created. And displayed view has view model without parameters (default constructor).

推荐答案

而不是在xaml中初始化DataContext

instead of initializing DataContext in xaml

<UserControl.DataContext>
    <local:PolaPrzewoznikowViewModel />
</UserControl.DataContext>

我建议使用DesignInstance:

<UserControl d:DataContext="{d:DesignInstance Type=local:PolaPrzewoznikowViewModel, 
                             IsDesignTimeCreatable=True}" ...>

它将在设计时为IntelliSense和设计人员提供足够的信息,但是不会在运行时创建新实例(WindowService中将只有DataContext)

It will give IntelliSense and designer enough information in design-time, but a new instance won't be created in run-time (there will only DataContext from WindowService)

这篇关于WPF/MVVM Windows服务,无需重置视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆