WPF MVVM中在ViewModel中关闭或者打开Window

原文: WPF MVVM中在ViewModel中关闭或者打开Window

这篇博客将介绍在MVVM模式ViewModel中关闭和打开View的方法。

1. ViewModel中关闭View

    public class MainViewModel
    {
        public DelegateCommand CloseWindowCommand { get; private set; }

        public MainViewModel()
        {
            CloseWindowCommand = new DelegateCommand(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)