WPF基于.Net Core (2)

在MainView.xaml.cs中添加DataContext进行MainView和MainViewModel的绑定

using HelloCore.ViewModel; using System.Windows; namespace HelloCore.View { /// <summary> /// MainView.xaml 的交互逻辑 /// </summary> public partial class MainView : Window { MainViewModel vm = new MainViewModel(); public MainView() { InitializeComponent(); this.DataContext = vm; } } } 2.5、修改App.xmal文件

修改App.xaml文件,删除StartupUri,添加启动事件以及异常捕捉事件

![image-20200711131032509](C:\Users\fangzhongwei\Desktop\WPF Net Core\image\image-20200711131032509.png)

<Application x:Class="HelloCore.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:HelloCore" Startup="Application_Startup" DispatcherUnhandledException="Application_DispatcherUnhandledException"> <Application.Resources> </Application.Resources> </Application> 2.6、修改App.xaml.cs文件 using HelloCore.View; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace HelloCore { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { MainView mainWindow; public App() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler); } private static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) { } /// <summary> /// 重写Starup函数,程序重这里启动 /// </summary> /// <param></param> /// <param></param> private void Application_Startup(object sender, StartupEventArgs e) { mainWindow = new MainView(); mainWindow.Show(); } /// <summary> /// 异常处理 /// </summary> /// <param></param> /// <param></param> private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { // .Net4.0及之前版本访问剪切板默写情况下可能失败报异常 // OpenClipboard HRESULT:0x800401D0 (CLIPBRD_E_CANT_OPEN)) var comException = e.Exception as System.Runtime.InteropServices.COMException; if (comException != null && comException.ErrorCode == -2147221040) { e.Handled = true; } // 未捕获的异常 e.Handled = true; } } }

2.7、启动程序,观看结果

到这里一个简单的基于.net core的WPF应用程序就完成啦,当然WPF真正的魅力没有展示出来,MVVM模式的意义大概是这样了,实现View和Model的分离

![image-20200711134557199](C:\Users\fangzhongwei\Desktop\WPF Net Core\image\image-20200711134557199.png)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpwjwj.html