这个功能应该常用与登录 后 主界面显示

Login 窗体

Main窗体

LoginViewModel

MainViewModel

首先定义俩个帮助类

WindowBehavior 和WindowManager

public class WindowBehavior : Behavior<Window>
{
/// <summary>
/// 关闭窗口
/// </summary>
public bool Close
{
get { return (bool)GetValue(CloseProperty); }
set { SetValue(CloseProperty, value); }
}
public static readonly DependencyProperty CloseProperty =
DependencyProperty.Register("Close", typeof(bool), typeof(WindowBehavior), new PropertyMetadata(false, OnCloseChanged));
private static void OnCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = ((WindowBehavior)d).AssociatedObject;
var newValue = (bool)e.NewValue;
if (newValue)
{
window.Close();
}
}

}
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();
}
}
public static void ShowDialog(string key, object VM)
{
if (_RegisterWindow.ContainsKey(key))
{
var win = (Window)Activator.CreateInstance((Type)_RegisterWindow[key]);
win.DataContext = VM;
win.ShowDialog();
}
}
}

在登录窗体里  Login窗体 增加Main窗体

public partial class LoginView : Window
{
public LoginView()
{
InitializeComponent();

DataContext = new LoginViewModel();
WindowManager.Register<MainView>("MainView");
}
}

在Login 界面上 增加行为

WPF MVVM下 关闭窗体 并打开新窗体_java

<i:Interaction.Behaviors>
<Helper:WindowBehavior Close="{Binding ToClose}"/>
</i:Interaction.Behaviors>

LoginViewModel 里增加属性 和命令

public LoginViewModel()
{

CMDLogin = new DeletegateCommand();
CMDLogin.ExecuteAction = new Action<object>(CMDLoginExecute);

}
/// <summary>
/// 是否关闭窗口
/// </summary>
private bool toClose = false;
public bool ToClose
{
get => toClose;
set
{
toClose = value;
if (toClose)
{
this.RaisePropertyChanged("ToClose");
}
}
}


#region 命令绑定及实现
public DeletegateCommand CMDLogin { get; set; }
private void CMDLoginExecute(object parameter)
{
OISGlobal.ShowMessage("Test", "Test", MSGTYPE.INFO);
WindowManager.Show("MainView", new MainViewModel());
ToClose = true;
}

登录界面的button 绑定命令

<Button x:Name="button" Content="登录" HorizontalAlignment="Left" Height="54" Margin="32,451,32,50" VerticalAlignment="Top" Width="408" Background="#FF1AB394" FontSize="22" Foreground="White" Padding="0" BorderBrush="White" FontFamily="Microsoft YaHei"  Command="{Binding CMDLogin}" CommandParameter="{Binding ElementName=Login}" />