如何在WPF .NET Core应用程序中启用控制台?

时间:2019-09-27 20:22:35

标签: c# wpf .net-core

我第一次尝试使用WPF .NET Core,在新的WPF .NET Framework项目中我经常做的一件事是打开控制台,但是尝试执行此操作时收到错误消息在.NET Core中。

在针对.NET Framework的传统WPF中,这非常简单;

  • 将App.xaml的构建操作设置为Page
  • 在某个地方定义一个Main方法,并用STAThreadAttribute标记它
  • 在项目设置中,将输出类型设置为“控制台应用程序”,并将“启动对象”设置为放置Main方法的任何位置

我在WPF .NET Core中复制了这些步骤,但是当我尝试更改App.xaml的生成操作时遇到错误

错误(在“属性”窗口的下拉菜单中选择“页面”后立即发生):

An error has occurred while saving the edited properties listed below:
    Build Action
One or more values are invalid. 
Cannot add 'App.xaml' to the project, because the path is explicitly excluded from the project 
(C:\Program Files\dotnet\sdk\3.0.100\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.NET.Sdk.WindowsDesktop.targets (45,5)).

有人知道解决此问题的方法,还是在WPF .NET Core中启用控制台的另一种方法?

2 个答案:

答案 0 :(得分:3)

设置以下属性将使您的 WPF 应用程序成为“控制台应用程序”

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <DisableWinExeOutputInference>true</DisableWinExeOutputInference>
</PropertyGroup>

对于 WPF 和 WinForms 应用程序,SDK 会自动将 OutputType 从 Exe 更改为 WinExe。见https://docs.microsoft.com/en-us/dotnet/core/compatibility/windows-forms/5.0/automatically-infer-winexe-output-type

答案 1 :(得分:0)

经过反复试验,我发现.csproj文件被弄乱了。我不知道它到底出了什么问题,我怀疑这与通过该版本的VS2019的“属性”窗口编辑项目有关。

我手动编辑了.csproj,如果它看起来如下所示,它将起作用:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
    <ApplicationIcon />
    <StartupObject>ProjectName.App</StartupObject>
  </PropertyGroup>

  <ItemGroup>
    <Page Include="App.xaml"></Page>
  </ItemGroup>

  <ItemGroup>
    <ApplicationDefinition Remove="App.xaml"></ApplicationDefinition>      <--- key part
  </ItemGroup>

</Project>

我检查了.csproj文件中是否有可用的.NET Framework项目,并且关键似乎是手动删除了App.xaml作为ApplicationDefinition,因为.NET Framework .csproj中没有该部分。