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接口

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input; namespace Common.Command
{
/// <summary>
/// 实现ICommand接口
/// </summary>
public class BaseCommand : ICommand
{
public Predicate<object> CanExecuteDelegate { get; set; }
public Action<object> ExecuteDelegate { get; set; } public BaseCommand(Action<object> execute)
{
ExecuteDelegate = execute;
} public BaseCommand(Action<object> execute, Predicate<object> canExecute)
{
CanExecuteDelegate = canExecute;
ExecuteDelegate = execute;
} public BaseCommand()
{
} /// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
public bool CanExecute(object parameter)
{
if (CanExecuteDelegate != null)
return CanExecuteDelegate(parameter);
return true;
} /// <summary>
/// Occurs when changes occur that affect whether the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
} remove
{
CommandManager.RequerySuggested -= value;
}
} /// <summary>
/// 执行
/// </summary>
public void Execute(object parameter)
{
try
{
if (ExecuteDelegate != null)
ExecuteDelegate(parameter);
}
catch (Exception ex)
{
string moudle = ExecuteDelegate.Method.DeclaringType.Name + ":" + ExecuteDelegate.Method.Name;
}
} /// <summary>
/// Raises the CanExecuteChanged event.
/// </summary>
public void InvalidateCanExecute()
{
CommandManager.InvalidateRequerySuggested();
}
}
}

2.3、实现INotifyPropertyChanged接口

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text; namespace Common.Command
{
/// <summary>
/// 实现INotifyPropertyChanged接口
/// </summary>
public class NotifyPropertyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
} public object Clone()
{
return this.MemberwiseClone();
}
}
}

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

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

2.3、添加MainViewModel.cs文件

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

using Common.Command;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input; namespace HelloCore.ViewModel
{
public class MainViewModel : NotifyPropertyBase
{
private string _result; /// <summary>
/// 绑定到界面上TextBox的Text属性上
/// </summary>
public string Result
{
get
{
return _result;
}
set
{
_result = value;
OnPropertyChanged("Result");
}
} private ICommand _helloCommand;
private ICommand _clearCommand; public ICommand HelloCommand
{
get
{
return this._helloCommand ?? (this._helloCommand = new BaseCommand()
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x =>
{
Result = "Hello Net Core";
}
});
}
} public ICommand ClearCommand
{
get
{
return this._clearCommand ?? (this._clearCommand = new BaseCommand()
{
CanExecuteDelegate = x => true,
ExecuteDelegate = x =>
{
Result = "";
}
});
}
}
}
}

2.4、通过DataContext绑定

在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 name="sender"></param>
/// <param name="e"></param>
private void Application_Startup(object sender, StartupEventArgs e)
{
mainWindow = new MainView();
mainWindow.Show();
} /// <summary>
/// 异常处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></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)

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. Cron表达式,springboot定时任务

    详细请看这篇博客 参考:https://blog.csdn.net/belonghuang157405/article/details/83410197 Cron表达式是一个字符串,字符串以5或6个空 ...

  2. 解决Celery 在Windows中搭建和使用的版本

    官网:http://docs.celeryproject.org/en/latest/faq.html#does-celery-support-windows 描述如下:表示Celery 4.0版本以 ...

  3. python基础:如何使用 pip 安装第三方库

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 在这个生活中处处都是大数据和人工智能的时代,总是能在各种角落看到 Pyth ...

  4. Arduino控制超声波检测与0.96OLED及串口显示

    Arduino控制超声波检测与0.96OLED及串口显示代码使用库共享(包括超声波检测与U8glib): 使用元件: 0.96寸 12864 I2C OLED 128x64规格 超声波检测模块 湿度模 ...

  5. cb10a_c++_顺序容器的操作3关系运算符

    cb10a_c++_cb09a_c++_顺序容器的操作3 2 顺序容器的操作3 3 关系运算符 4 所有的容器类型都可以使用 5 比较的容器必须具有相同的容器类型,double不能与int作比较 6 ...

  6. OS_进程调度:C++实现

    实验二.进程调度模拟实验 一.实验目的: 本实验模拟在单处理机环境下的处理机调度,帮助理解进程调度的概念,深入了解进程控制块的功能,以及进程的创建.撤销和进程各个状态间的转换过程. 二.实验内容: 进 ...

  7. WeChair项目Beta冲刺(3/10)

    团队项目进行情况 1.昨日进展    Beta冲刺第三天 昨日进展: 昨天工作开始有条不紊地进行着,大家积极交流 2.今日安排 前端:扫码占座功能和预约功能并行开发 后端:扫码占座后端逻辑和预约功能逻 ...

  8. 在运行时生成C# .NET类

    ​本文译自​:​Generating C# .NET Classes at Runtime 作者:WedPort 在我的C#职业生涯中,有几次我不得不在运行时生成新的类型.希望把它写下来能帮助有相同应 ...

  9. SpringCloud教程第2篇:Ribbon(F版本)

    一.ribbon简介 Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign.在这一篇文章首先讲解下基于ribbon+rest. ribbon是一 ...

  10. 组合注解(Annotation)

    import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.an ...