本文记录了对Tutorial: Modernize a WPF app的尝试。
环境
- Windows 11
- Visual Studio 2022
- .NET SDK 6
下载https://github.com/microsoft/AppConsult-WinAppsModernizationWorkshop/releases/download/1.1/WinAppsModernizationWorkshop.zip并解压, 里面有6个练习。
Part 1: Migrate the Contoso Expenses app to .NET Core 3
进入Exercise1 的01-Start目录(里面有ContosoExpenses.csproj),创建ContosoExpenses.Core.csproj内容如下:
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp6.0</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
将ContosoExpenses.Core.csproj添加到解决方案。
对于ContosoExpenses.Data,直接将其替换成:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
</Project>
关于.NET Standard和.NET Framework的区别,看https://docs.microsoft.com/en-us/dotnet/standard/net-standard
删除ContosoExpenses.Data的Packages.config
,添加最新的NuGet包Bogus和LiteDB。
打开ContosoExpenses.Data.csproj,可以看到:
<ItemGroup>
<PackageReference Include="Bogus" Version="34.0.1" />
<PackageReference Include="LiteDB" Version="5.0.11" />
</ItemGroup>
回到ContosoExpenses.Core,删除其Packages.config
,添加最新的NuGet包:
- MvvmLightLibsStd10 (其实已经被标注废弃了)
- Unity
次级依赖的包会自动添加。
ContosoExpenses.Core添加一个到ContosoExpenses.Data的引用。
将<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
添加到ContosoExpenses.Core和ContosoExpenses.Data,避免生成重复的配装件属性。
构建工程,可以看到错误:
Services\RegistryService.cs(9,26,9,34): error CS0103: The name 'Registry' does not exist in the current context Services\RegistryService.cs(12,26,12,34): error CS0103: The name 'Registry' does not exist in the current context Services\RegistryService.cs(12,97,12,123): error CS0103: The name 'RegistryKeyPermissionCheck' does not exist in the current context
解决办法是给ContosoExpenses.Data安装Microsoft.Windows.Compatibility这个NuGet包(一个相当大的NuGet包)。然后ContosoExpenses.Data就可以构建成功。
接下来构建ContosoExpenses.Core
,出现一下错误:
Error NETSDK1136 The target platform must be set to Windows (usually by including '-windows' in the TargetFramework property) when using Windows Forms or WPF, or referencing projects or packages that do so. ContosoExpenses.Core
解决办法是将<TargetFramework>netcoreapp6.0</TargetFramework>
改成<TargetFramework>net6.0-windows</TargetFramework>
,参考 How to solve the error :NETSDK1136 #14297
ContosoExpenses.Core可构建成功,但之后运行出现:
IOException: Cannot locate resource 'images/expensesbackground.jpg'.
需要编辑ContosoExpenses.Core.csproj文件,添加:
<ItemGroup>
<Content Include="Images/*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
然后在ContosoExpenses.Core的辖属中,将Icon改为Images\contoso.ico
。
改完之后,终于成功运行,满头大汗~