Как перенести проекты Wpf в новый формат VS2017
Я перевожу свои проекты в новый формат visual studio 2017, который прекрасно работает для всех стандартных библиотек, только теперь у меня возникают проблемы с моими библиотеками пользовательского интерфейса, где я использую Wpf / Xaml.
Я не могу понять, как это сделать для моих пользовательских элементов управления. Старый элемент больше не действителен.
У кого-нибудь есть идея, как это сделать, или если это вообще возможно.
7 ответов
Есть Sunburst.NET.Sdk.WPF, который позволяет использовать его как.NET SDK. Вот полный пример для приложения WPF, где любой .cs
а также .xaml
файлы будут включены автоматически:
<Project Sdk="Sunburst.NET.Sdk.WPF/1.0.47">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net40</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../WpfMath/WpfMath.csproj" />
</ItemGroup>
</Project>
Когда вы строите этот проект с msbuild
(в частности, мне не повезло с dotnet build
хотя), он автоматически загрузит SDK из NuGet и все настроит.
Вы можете использовать шаблон ниже, чтобы заменить старый.csproj на. Это решает пару вопросов, которые были у других людей.
- Вы не должны включать посредника
*.g.cs
файлы, как некоторые предложили сделать. - нет
Main not found
ошибка произойдет. - нет
Unable to run your project. The "RunCommand" property is not defined.
ошибка произойдет. - Включает в себя уже настроенные настройки и ресурсы по умолчанию.
Шаблон:
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0">
<PropertyGroup>
<LanguageTargets>$(MSBuildExtensionsPath)\$(VisualStudioVersion)\Bin\Microsoft.CSharp.targets</LanguageTargets>
<TargetFramework>net47</TargetFramework>
<OutputType>WinExe</OutputType>
<StartupObject />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<!-- App.xaml -->
<ApplicationDefinition Include="App.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
</ApplicationDefinition>
<!-- XAML elements -->
<Page Include="**\*.xaml" Exclude="App.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
</Page>
<Compile Update="**\*.xaml.cs" SubType="Code" DependentUpon="%(Filename)" />
<!-- Resources -->
<EmbeddedResource Update="Properties\Resources.resx" Generator="ResXFileCodeGenerator" LastGenOutput="Resources.Designer.cs" />
<Compile Update="Properties\Resources.Designer.cs" AutoGen="True" DependentUpon="Resources.resx" DesignTime="True" />
<!-- Settings -->
<None Update="Properties\Settings.settings" Generator="SettingsSingleFileGenerator" LastGenOutput="Settings.Designer.cs" />
<Compile Update="Properties\Settings.Designer.cs" AutoGen="True" DependentUpon="Settings.settings" />
</ItemGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System.Xaml" />
<Reference Include="WindowsBase" />
</ItemGroup>
</Project>
После некоторых поисков и проб и ошибок я получил это работает!
Это последний wpf csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LanguageTargets>$(MSBuildExtensionsPath)\$(VisualStudioVersion)\Bin\Microsoft.CSharp.targets</LanguageTargets>
<TargetFrameworks>net451</TargetFrameworks>
<RootNamespace>MyWpfLibrary</RootNamespace>
<AssemblyName>MyWpfLibrary</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Rx-Xaml" Version="2.2.5" />
<PackageReference Include="reactiveui-core" Version="7.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="MyOtherLibrary.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="ReachFramework" />
<Reference Include="System.Net" />
<Reference Include="System.Printing" />
<Reference Include="System.Xaml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx" Generator="ResXFileCodeGenerator" LastGenOutput="Resources.Designer.cs" />
<Compile Update="Properties\Resources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Resources.resx"/>
<Page Include="**\*.xaml" SubType="Designer" Generator="MSBuild:Compile" />
<Compile Update="**\*.xaml.cs" SubType="Designer" DependentUpon="%(Filename)" />
<Resource Include="Fonts\*.otf" />
<Resource Include="Images\*.png" />
</ItemGroup>
<Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" />
</Project>
Вышеупомянутое решение работает для Wpf dll, но я отменил его, потому что после этого изменения Resharper и дизайнер Visual Studio перестали функционировать. Главным образом потому, что они не могли соединить xaml и программный код во время разработки. Но проект компилируется и работает.
Для исполняемого файла wpf вам нужно сделать следующее:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LanguageTargets>$(MSBuildExtensionsPath)\$(VisualStudioVersion)\Bin\Microsoft.CSharp.targets</LanguageTargets>
<TargetFramework>net451</TargetFramework>
<OutputType>WinExe</OutputType>
<RootNamespace>MyNamespace</RootNamespace>
<AssemblyName>MyExe</AssemblyName>
<ApplicationIcon>MyExe.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<StartupObject>MyNamespace.App</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System.Xaml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx" Generator="ResXFileCodeGenerator" LastGenOutput="Resources.Designer.cs" />
<Compile Update="Properties\Resources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Resources.resx" />
<None Update="Properties\Settings.settings" Generator="SettingsSingleFileGenerator" LastGenOutput="Settings.Designer.cs" />
<Compile Update="Properties\Settings.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Settings.settings" />
<Page Include="MainWindow.xaml" SubType="Designer" Generator="MSBuild:Compile" />
<Compile Update="MainWindow.xaml.cs" DependentUpon="MainWindow.xaml" />
<Resource Include="Images\*.png" />
<ApplicationDefinition Include="App.xaml" SubType="Designer" Generator="XamlIntelliSenseFileGenerator" />
<Compile Update="App.xaml.cs" DependentUpon="App.xaml" />
</ItemGroup>
<Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" />
</Project>
Теперь, когда выпущен.NET Core 3, вы должны использовать его, если можете.
Но в противном случае я обнаружил, что могу создать отдельный общий проект только для элементов XAML и могу ссылаться на этот проект из проекта в стиле SDK. Все строится правильно.
Обратите внимание, что конструктор XAML не работает - нет Intellisense или красных волнистых линий. Visual Studio открывает файлы XAML с помощью редактора XML.
Приведенные выше решения могут не работать с Xamarin.Platforms.WPF на VS2019.
Вот проект (на основе предыдущих ответов), разработанный для платформы.net (а не для основного приложения.net), но может обрабатывать стандартные зависимости.net:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<RootNamespace>TestWPF</RootNamespace>
<AssemblyName>TestWPF</AssemblyName>
<TargetFramework>net461</TargetFramework>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugType>full</DebugType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugType>pdbonly</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.Platforms" Version="3.0.0" />
<PackageReference Include="Xamarin.Forms" Version="4.2.0.848062" />
<PackageReference Include="Xamarin.Forms.Platform.WPF" Version="4.2.0.848062" />
</ItemGroup>
<ItemGroup>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="WindowsBase" />
<Reference Include="System.Xaml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx" Generator="ResXFileCodeGenerator" LastGenOutput="Resources.Designer.cs" />
<Compile Update="Properties\Resources.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Resources.resx" />
<None Update="Properties\Settings.settings" Generator="SettingsSingleFileGenerator" LastGenOutput="Settings.Designer.cs"/>
<Compile Update="Properties\Settings.Designer.cs" DesignTime="True" AutoGen="True" DependentUpon="Settings.settings" />
<ApplicationDefinition Include="App.xaml" Generator="MSBuild:Compile" />
<Page Include="**\*.xaml" Exclude="App.xaml" SubType="Designer" Generator="MSBuild:Compile" />
<Compile Update="**\*.xaml.cs" SubType="Designer" DependentUpon="%(Filename)" />
<EmbeddedResource Remove="**\*.xaml" />
</ItemGroup>
<Import Project="$(MSBuildSDKExtrasTargets)" Condition="Exists('$(MSBuildSDKExtrasTargets)')" />
</Project>
Используйте официальную утилиту обновления для преобразования проекта:
dotnet tool install --global Project2015To2017.Migrate2019.Tool
dotnet migrate-2019 wizard MyTestProject.csproj
Работает как для файлов проекта, так и для файлов решения. Больше информации здесь