MvvmLight 使用
1 Nuget 下载 MvvmLight
2.安装过程中帮你创建viewModel文件夹,里面有偶MainViewModel 和viewModelLocator
3.将viewModelLocator里面的using Microsoft.Practices.ServiceLocation; 替换成using CommonServiceLocator;
Messenger的使用
ViewModel和View的交互
在View中使用Token注册
public XXXPage() { InitializeComponent(); Messenger.Default.Register<string>(this, "SettingsPage", OnMsg); this.Unloaded += (s, e) => Messenger.Default.Unregister(this); }
"SettingPage"是一个自己命名的Token,
发送方代码如下
Messenger.Default.Send<string>(“SendString”, "SettingsPage");
第二个参数token表示向对应的接受方发送消息,接受的处理函数OnMsg就会执行。
ViewModel和ViewModel的交互
在A 的构造函数中
Messenger.Default.Register<String>(this,"Message",ShowReceiveInfo);
在B中
Messenger.Default.Send<String>(SendInfo, "Message");
在异步线程中进行主线程中的操作
DispatcherHelper.CheckBeginInvokeOnUI(() => { Messenger.Default.Send<TopUserInfo>(ui, "UserMessenger"); });
绑定的说明
{Binding mock.Intro,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}
Mode默认操作:绑定的模式根据实际情况来定,如果是可编辑的就是TwoWay,只读的就是OneWay,所以
Mode 使用默认即可,数据源有变化,UI会更新,UI有变化,数据源会更新。
UpdateSourceTrigger说明了UI的值有变化,怎么通知数据源,
Exlicit一般不用。
默认LostFocus,
所以要用,一般就是
UpdateSourceTrigger=PropertyChanged
Explicit | 当应用程序调用 UpdateSource 方法时生效 |
LostFocus | 失去焦点的时候触发 |
PropertyChanged | 数据属性改变的时候触发 |
全局异常处理

private void Application_Startup(object sender, StartupEventArgs e) { InitExceptionHandler(); } private void InitExceptionHandler() { //UI线程未捕获异常处理事件 this.DispatcherUnhandledException+=(sender, e)=> { e.Handled = true; OnUnhandledException(e.Exception); }; //Task线程内未捕获异常处理事件 TaskScheduler.UnobservedTaskException += (sender, e) => { OnUnhandledException(e.Exception); }; //非UI线程未捕获异常处理事件 AppDomain.CurrentDomain.UnhandledException += (sender, e) => { if(e.ExceptionObject is Exception) { OnUnhandledException(e.ExceptionObject as Exception); } else { System.Console.WriteLine($"Exception :{e.ExceptionObject}"); } }; } private static void OnUnhandledException(Exception e) { App.Current.Dispatcher.Invoke(() => { lock(App.Current) { MessageBox.Show(e.ToString(),"全局异常",MessageBoxButton.OK,MessageBoxImage.Error); } }); }
分为
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话