WPF 在MVVM模式下弹出子窗体的方式
主要是通过一个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 WindowRegister { 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); } } |
添加一个窗体,并注册子窗体, this.Register<Window1>("Window1");
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this .DataContext = new MainWindowViewModel(); this .Register<Window1>( "Effects" ); } } |
添加ViewModel,继承自ViewModelBase,并在对应的命令中弹出子窗体Window1
private DelegateCommand<Window> _effectCommand = null ; public DelegateCommand<Window> EffectCommand { set { _effectCommand = value; } get { if (_effectCommand == null ) { _effectCommand = new DelegateCommand<Window>(Effect); } return _effectCommand; } } void Effect(Window window) { WindowManager.ShowDialog( "Effects" , this ); } |
"唯有高屋建瓴,方可水到渠成"
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
2014-08-07 CSS外框高度自动适应
2013-08-07 HTML DOM 基础知识,成为javascript晋级高手的必备手册