WPF基于.Net Core

因为最近.net core的热门,所以想实现一下.net core框架下的WPF项目,还是MVVM模式,下面就开始吧,简单做一个计算器吧。

  • 使用VS2019作为开发工具

  • 实现MVVM模式

1、实现基础项目

使用VS2019新建WPF App项目

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

项目名称Common

1.1、修改项目属性

  • 删除项目MainWindow.xaml以及MainWindow.xaml.cs文件

  • 删除App.xaml和App.xaml.cs文件

  • 修改项目输出为类库

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

  • 添加Command文件夹

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

2.2、实现ICommand接口

定义BaseCommand类实现ICommand接口

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Input;
  5. namespace Common.Command
  6. {
  7. /// <summary>
  8. /// 实现ICommand接口
  9. /// </summary>
  10. public class BaseCommand : ICommand
  11. {
  12. public Predicate<object> CanExecuteDelegate { get; set; }
  13. public Action<object> ExecuteDelegate { get; set; }
  14. public BaseCommand(Action<object> execute)
  15. {
  16. ExecuteDelegate = execute;
  17. }
  18. public BaseCommand(Action<object> execute, Predicate<object> canExecute)
  19. {
  20. CanExecuteDelegate = canExecute;
  21. ExecuteDelegate = execute;
  22. }
  23. public BaseCommand()
  24. {
  25. }
  26. /// <summary>
  27. /// Defines the method that determines whether the command can execute in its current state.
  28. /// </summary>
  29. public bool CanExecute(object parameter)
  30. {
  31. if (CanExecuteDelegate != null)
  32. return CanExecuteDelegate(parameter);
  33. return true;
  34. }
  35. /// <summary>
  36. /// Occurs when changes occur that affect whether the command should execute.
  37. /// </summary>
  38. public event EventHandler CanExecuteChanged
  39. {
  40. add
  41. {
  42. CommandManager.RequerySuggested += value;
  43. }
  44. remove
  45. {
  46. CommandManager.RequerySuggested -= value;
  47. }
  48. }
  49. /// <summary>
  50. /// 执行
  51. /// </summary>
  52. public void Execute(object parameter)
  53. {
  54. try
  55. {
  56. if (ExecuteDelegate != null)
  57. ExecuteDelegate(parameter);
  58. }
  59. catch (Exception ex)
  60. {
  61. string moudle = ExecuteDelegate.Method.DeclaringType.Name + ":" + ExecuteDelegate.Method.Name;
  62. }
  63. }
  64. /// <summary>
  65. /// Raises the CanExecuteChanged event.
  66. /// </summary>
  67. public void InvalidateCanExecute()
  68. {
  69. CommandManager.InvalidateRequerySuggested();
  70. }
  71. }
  72. }

2.3、实现INotifyPropertyChanged接口

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Text;
  5. namespace Common.Command
  6. {
  7. /// <summary>
  8. /// 实现INotifyPropertyChanged接口
  9. /// </summary>
  10. public class NotifyPropertyBase : INotifyPropertyChanged
  11. {
  12. public event PropertyChangedEventHandler PropertyChanged;
  13. public void OnPropertyChanged(string propertyName)
  14. {
  15. PropertyChangedEventHandler handler = this.PropertyChanged;
  16. if (handler != null)
  17. {
  18. handler(this, new PropertyChangedEventArgs(propertyName));
  19. }
  20. }
  21. public object Clone()
  22. {
  23. return this.MemberwiseClone();
  24. }
  25. }
  26. }

2、主程序HelloCore

2.1、新建WPF APP项目

项目名称为HelloCore

新建View、ViewModel、Model三个文件夹

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

删除MainWindow.xaml

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

2.2、添加窗体MainView.xaml

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

修改MainView.xaml

  1. <Window x:Class="HelloCore.View.MainView"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:HelloCore.View"
  7. mc:Ignorable="d"
  8. Title="HelloCore" Height="350" Width="600">
  9. <Grid>
  10. <Grid.RowDefinitions>
  11. <RowDefinition Height="*"/>
  12. <RowDefinition Height="Auto"/>
  13. </Grid.RowDefinitions>
  14. <TextBox Text="{Binding Result}" Margin="5"/>
  15. <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
  16. <Button Content="HelloCore" Command="{Binding HelloCommand}" Margin="10" Width="80" Height="30"/>
  17. <Button Content="Clear" Command="{Binding ClearCommand}" Margin="10" Width="80" Height="30"/>
  18. </StackPanel>
  19. </Grid>
  20. </Window>

2.3、添加MainViewModel.cs文件

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

  1. using Common.Command;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Windows.Input;
  6. namespace HelloCore.ViewModel
  7. {
  8. public class MainViewModel : NotifyPropertyBase
  9. {
  10. private string _result;
  11. /// <summary>
  12. /// 绑定到界面上TextBox的Text属性上
  13. /// </summary>
  14. public string Result
  15. {
  16. get
  17. {
  18. return _result;
  19. }
  20. set
  21. {
  22. _result = value;
  23. OnPropertyChanged("Result");
  24. }
  25. }
  26. private ICommand _helloCommand;
  27. private ICommand _clearCommand;
  28. public ICommand HelloCommand
  29. {
  30. get
  31. {
  32. return this._helloCommand ?? (this._helloCommand = new BaseCommand()
  33. {
  34. CanExecuteDelegate = x => true,
  35. ExecuteDelegate = x =>
  36. {
  37. Result = "Hello Net Core";
  38. }
  39. });
  40. }
  41. }
  42. public ICommand ClearCommand
  43. {
  44. get
  45. {
  46. return this._clearCommand ?? (this._clearCommand = new BaseCommand()
  47. {
  48. CanExecuteDelegate = x => true,
  49. ExecuteDelegate = x =>
  50. {
  51. Result = "";
  52. }
  53. });
  54. }
  55. }
  56. }
  57. }

2.4、通过DataContext绑定

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

  1. using HelloCore.ViewModel;
  2. using System.Windows;
  3. namespace HelloCore.View
  4. {
  5. /// <summary>
  6. /// MainView.xaml 的交互逻辑
  7. /// </summary>
  8. public partial class MainView : Window
  9. {
  10. MainViewModel vm = new MainViewModel();
  11. public MainView()
  12. {
  13. InitializeComponent();
  14. this.DataContext = vm;
  15. }
  16. }
  17. }

2.5、修改App.xmal文件

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

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

  1. <Application x:Class="HelloCore.App"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:local="clr-namespace:HelloCore"
  5. Startup="Application_Startup"
  6. DispatcherUnhandledException="Application_DispatcherUnhandledException">
  7. <Application.Resources>
  8. </Application.Resources>
  9. </Application>

2.6、修改App.xaml.cs文件

  1. using HelloCore.View;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. namespace HelloCore
  10. {
  11. /// <summary>
  12. /// Interaction logic for App.xaml
  13. /// </summary>
  14. public partial class App : Application
  15. {
  16. MainView mainWindow;
  17. public App()
  18. {
  19. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);
  20. }
  21. private static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
  22. {
  23. }
  24. /// <summary>
  25. /// 重写Starup函数,程序重这里启动
  26. /// </summary>
  27. /// <param name="sender"></param>
  28. /// <param name="e"></param>
  29. private void Application_Startup(object sender, StartupEventArgs e)
  30. {
  31. mainWindow = new MainView();
  32. mainWindow.Show();
  33. }
  34. /// <summary>
  35. /// 异常处理
  36. /// </summary>
  37. /// <param name="sender"></param>
  38. /// <param name="e"></param>
  39. private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
  40. {
  41. // .Net4.0及之前版本访问剪切板默写情况下可能失败报异常
  42. // OpenClipboard HRESULT:0x800401D0 (CLIPBRD_E_CANT_OPEN))
  43. var comException = e.Exception as System.Runtime.InteropServices.COMException;
  44. if (comException != null && comException.ErrorCode == -2147221040)
  45. {
  46. e.Handled = true;
  47. }
  48. // 未捕获的异常
  49. e.Handled = true;
  50. }
  51. }
  52. }

2.7、启动程序,观看结果

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

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

WPF基于.Net Core的更多相关文章

  1. 将基于 .NET Framework 的 WPF 项目迁移到基于 .NET Core 3

    在 Connect(); 2018 大会上,微软发布了 .NET Core 3 Preview,以及基于 .NET Core 3 的 WPF:同时还发布了 Visual Studio 2019 预览版 ...

  2. 如何创建一个基于 .NET Core 3 的 WPF 项目

    在 Connect(); 2018 大会上,微软发布了 .NET Core 3 Preview,以及基于 .NET Core 3 的 WPF:同时还发布了 Visual Studio 2019 预览版 ...

  3. WPF窗体中嵌入/使用WinForm类/控件(基于.NET Core)

    如题,WPF中嵌入WinForm的做法,网络上已经很多示例,都是基于.NET XXX版的. 今天King様在尝试WPF(基于.NET Core 3.1)中加入Windows.Forms.ColorDi ...

  4. 一个技术汪的开源梦 —— 基于 .Net Core 的公共组件之 Http 请求客户端

    一个技术汪的开源梦 —— 目录 想必大家在项目开发的时候应该都在程序中调用过自己内部的接口或者使用过第三方提供的接口,咱今天不讨论 REST ,最常用的请求应该就是 GET 和 POST 了,那下面开 ...

  5. .NET跨平台之旅:基于.NET Core改写EnyimMemcached,实现Linux上访问memcached缓存

    注:支持 .NET Core 的 memcached 客户端 EnyimMemcachedCore 的 NuGet 包下载地址:https://www.nuget.org/packages/Enyim ...

  6. 基于.NET Core的Hypertext Application Language(HAL)开发库

    HAL,全称为Hypertext Application Language,它是一种简单的数据格式,它能以一种简单.统一的形式,在API中引入超链接特性,使得API的可发现性(discoverable ...

  7. 基于DotNet Core的RPC框架(一) DotBPE.RPC快速开始

    0x00 简介 DotBPE.RPC是一款基于dotnet core编写的RPC框架,而它的爸爸DotBPE,目标是实现一个开箱即用的微服务框架,但是它还差点意思,还仅仅在构思和尝试的阶段.但不管怎么 ...

  8. 基于.NET CORE微服务框架 -surging的介绍和简单示例 (开源)

    一.前言 至今为止编程开发已经11个年头,从 VB6.0,ASP时代到ASP.NET再到MVC, 从中见证了.NET技术发展,从无畏无知的懵懂少年,到现在的中年大叔,从中的酸甜苦辣也只有本人自知.随着 ...

  9. 基于.NET CORE微服务框架 -谈谈surging API网关

    1.前言 对于最近surging更新的API 网关大家也有所关注,也收到了不少反馈提出是否能介绍下Api网关,那么我们将在此篇文章中剥析下surging的Api 网关 开源地址:https://git ...

随机推荐

  1. 数值格式化 NumberFormat、 DecimalFormat、 RoundingMode

    NumberFormat [简介] java.text.NumberFormat extends java.text.Format extends java.lang.Object 实现的接口:Ser ...

  2. C# .net framework .net core 3.1 请求参数校验, DataAnnotations, 自定义参数校验

    前言 在实际应用场景中我们常常要对接口的入参进行校验, 例如分页大小是否正确, 必填参数是否已经填写等等. 最简单的实现方式如下图, 这种在实际开发中代码过于冗余, 而且不灵活. 今天介绍一种统一参数 ...

  3. 最全的DOM事件笔记

    1. DOM事件模型 DOM是微软和网景发生"浏览器大战"时期留下的产物,后来被"W3C"进行标准化,标准化一代代升级与改进,目前已经推行至第四代,即 leve ...

  4. ArchLinux的安装

    ArichLinux安装教程 Arch Linux 于 2002 年发布,由 Aaron Grifin 领头,是当下最热门的 Linux 发行版之一.从设计上说,Arch Linux 试图给用户提供简 ...

  5. (二)log4j 配置详解

    原文链接:https://blog.csdn.net/liupeifeng3514/article/details/79625013 1.配置根logger log4j.rootLogger = de ...

  6. 使用python,pytorch求海森Hessian矩阵

    考虑一个函数$y=f(\textbf{x}) (R^n\rightarrow R)$,y的Hessian矩阵定义如下: 考虑一个函数:$$f(x)=b^Tx+\frac{1}{2}x^{T}Ax\\其 ...

  7. Java根据模板生成Word文档

    一,首先制作模板 1.先做一个Word文档, 2.打开Word,然后另存为*.xml文件 3.最后修改*.xml文件的后缀名为*.ftl 二,打开项目编辑器Idea,在pom文件中引入相关架包依赖(我 ...

  8. Oracle SQL调优系列之SQL Monitor Report

    @ 目录 1.SQL Monitor简介 2.捕捉sql的前提 3.SQL Monitor 参数设置 4.SQL Monitor Report 4.1.SQL_ID获取 4.2.Text文本格式 4. ...

  9. C# CLosedXML四句代码搞定DataTable数据导出到Excel

    最近用到DataTable导出到Excel,网上看了一下,都不怎么好使,逛了下GitHub一下完美解决了 用到的.net库CLosedXML,这个库用于读取,处理和写入Excel 2007+(.xls ...

  10. 03 . 二进制部署kubernetes1.18.4

    简介 目前生产部署kubernetes集群主要两种方式 kubeadm Kubeadm是一个K8s部署工具,提供kubeadm init和kubeadm join,用于快速部署Kubernetes集群 ...