WPF MVVM中在ViewModel中关闭或者打开Window
Posted Yang-Fei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF MVVM中在ViewModel中关闭或者打开Window相关的知识,希望对你有一定的参考价值。
这篇博客将介绍在MVVM模式ViewModel中关闭和打开View的方法。
1. ViewModel中关闭View
public class MainViewModel { public DelegateCommand<Window> CloseWindowCommand { get; private set; } public MainViewModel() { CloseWindowCommand = new DelegateCommand<Window>(CloseWindow); } private void CloseWindow(Window window) { if(window != null) { window.Close(); } } }
<Window x:Class="MvvmCloseWindowApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:MvvmCloseWindowApp" mc:Ignorable="d" x:Name="MWindow" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Content="Close Window" Width="100" Height="25" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding ElementName=MWindow}" /> </Grid> </Window>
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); } }
感谢您的阅读,代码点击这里下载。
以上是关于WPF MVVM中在ViewModel中关闭或者打开Window的主要内容,如果未能解决你的问题,请参考以下文章
如何从 ViewModel 命令生成的线程中关闭窗口? [复制]