WPF/MVVM windowsservice 没有视图模型重置 [英] WPF/MVVM windowsservice without viewmodel reset
问题描述
我想从我的视图模型创建视图中删除
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 windowsservice 没有视图模型重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!