主要是通過一個WindowManager管理類,在window背景代碼中通過WindowManager注冊需要彈出的窗體類型,在ViewModel通過WindowManager的Show方法,顯示出來。
WindowManager代碼如下:
public static class WindowManager
{
private static Hashtable _RegisterWindow = new Hashtable();
public static void Regiter<T>(string key)
{
_RegisterWindow.Add(key, typeof(T));
}
public static void Regiter(string key, Type t)
{
if (!_RegisterWindow.ContainsKey(key))
_RegisterWindow.Add(key, t);
}
public static void Remove(string key)
{
if (_RegisterWindow.ContainsKey(key))
_RegisterWindow.Remove(key);
}
public static void ShowDialog(string key, object VM)
{
if (!_RegisterWindow.ContainsKey(key))
{
throw (new Exception("沒有注冊此鍵!"));
}
var win = (Window)Activator.CreateInstance((Type)_RegisterWindow[key]);
win.DataContext = VM;
win.ShowDialog();
}
}
做一個擴充方法,将子窗體注冊方法擴充到Window類型的對象上。
public static class WindowExt
{
public static void Register(this Window win, string key)
{
WindowManager.Regiter(key, win.GetType());
}
public static void Register(this Window win,string key,Type t)
{
WindowManager.Regiter(key,t);
}
public static void Register<T>(this Window win, string key)
{
WindowManager.Regiter<T>(key);
}
}
添加一個ViewModelBase,并在類中添加ShowDialog方法,這樣所有繼承的ViewModel都有這個方法
public class ViewModelBase
{
public void ShowDialog(string key,object vm)
{
WindowManager.ShowDialog(key,vm);
}
public void ShowMessage(string mes,string title="",MessageBoxButton buttons= MessageBoxButton.OK)
{
MessageBox.Show(mes,title,buttons);
}
}
添加一個窗體,并注冊子窗體, this.Register<Window1>("Window1");
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
this.Register<Window1>("Window1");
}
}
添加ViewModel,繼承自ViewModelBase,并在對應的指令中彈出子窗體Window1
public class MainWindowViewModel:ViewModelBase
{
public MainWindowViewModel()
{
BtnCommand = new DelegateCommand(ExecuteBtn);
}
public DelegateCommand BtnCommand { get; set; }
private void ExecuteBtn()
{
ShowDialog("Window1",this);
}
}
這樣子窗體就彈出來了。