本文共 1305 字,大约阅读时间需要 4 分钟。
这篇博客将介绍在MVVM模式ViewModel中关闭和打开View的方法。
1. ViewModel中关闭View
public class MainViewModel { public DelegateCommandCloseWindowCommand { get; private set; } public MainViewModel() { CloseWindowCommand = new DelegateCommand (CloseWindow); } private void CloseWindow(Window window) { if(window != null) { window.Close(); } } }
2. 在ViewModel中打开Window
public interface IWindowService { void ShowWindow(object viewModel); }
public class SecondWindowService : IWindowService { public void ShowWindow(object viewModel) { var second = new SecondWindow(); second.DataContext = viewModel; second.Show(); } }
class MainViewModel { public DelegateCommand OpenNewWindow { get; private set; } public MainViewModel() { OpenNewWindow = new DelegateCommand(OpenWindow); } private void OpenWindow() { SecondWindowService service = new SecondWindowService(); SecondViewModel viewModel = new SecondViewModel(); service.ShowWindow(viewModel); } }
感谢您的阅读,代码点击下载。
转载地址:http://mxyqa.baihongyu.com/