1、在"Common"文件夹新建“WindowManager.cs”类
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace LoginDome.ViewModel.Common
{
/// <summary>
/// 窗口管理器
/// </summary>
public static class WindowManager
{
private static Hashtable _RegisterWindow = new Hashtable();
public static void Register<T>(string key)
{
if (!_RegisterWindow.Contains(key))
{
_RegisterWindow.Add(key, typeof(T));
}
}
public static void Register(string key,Type t)
{
if (!_RegisterWindow.Contains(key))
{
_RegisterWindow.Add(key, t);
}
}
public static void Remove(string key)
{
if (_RegisterWindow.ContainsKey(key))
{
_RegisterWindow.Remove(key);
}
}
public static void Show(string key,object VM)
{
if (_RegisterWindow.ContainsKey(key))
{
var win = (Window)Activator.CreateInstance((Type)_RegisterWindow[key]);
win.DataContext = VM;
win.Show();
}
}
}
}
2、然后在“LoginViewModel.xaml.cs”添加一句代码:
using LoginDome.Login;
using LoginDome.ViewModel.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace LoginDome
{
/// <summary>
/// LoginWindow.xaml 的交互逻辑
/// </summary>
public partial class LoginWindow : Window
{
public LoginWindow()
{
InitializeComponent();
this.DataContext = new LoginViewModel();
//打开窗口
WindowManager.Register<MainWindow>("MainWindow");
}
}
}
3、然后在需要打开窗口的地方,添加一句代码:
**一、LoginWindow.xaml**
<Button Command="{Binding ClickLoginCommand}" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" Width="150" Height="40" FontSize="18" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0 5 0 0">登 陆</Button>
**二、LoginWindow.xaml.cs**
//登录-按钮
private BaseCommand clickLoginCommand;
public BaseCommand ClickLoginCommand
{
get
{
if(clickLoginCommand == null)
{
clickLoginCommand = new BaseCommand(new Action<object>(o =>
{
//打开新窗口
WindowManager.Show("MainWindow", null);
}));
}
return clickLoginCommand;
}
}
执行结果: