码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-04-04 22:42:16      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:

这篇博客将介绍在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

标签:

原文地址:http://www.cnblogs.com/yang-fei/p/5352838.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!