Search code examples
c#wpf.net-core.net-8.0

Why is it not possible to reference PresentationCore.dll without <UseWPF>true</UseWPF>


I try to include a WPF-Window into a ConsoleApp. For this, I have referenced

  • PresentationCore.dll
  • PresentationFramework.dll
  • WindowsBase.dll

But when I try to execute the App, I get the Exception

System.BadImageFormatException HResult=0x80131058 Message=Could not load file or assembly 'PresentationFramework, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Reference assemblies cannot be loaded for execution. (0x80131058)
Source= StackTrace:

Inner Exception 1: BadImageFormatException: Cannot load a reference assembly for execution.

I know that I can include <UseWPF>true</UseWPF> but I want to understand, why this is necessary and it is not enough to reference the WPF-Framework (like it was in .NET 4.8).

Thanks for your explenation.


Solution

  • From MSBuild reference for .NET Desktop SDK projects: Enable .NET Desktop SDK section:

    To use WinForms or WPF, configure your project file. .NET 5 and later versions:

    • Target the .NET SDK Microsoft.NET.Sdk.
    • Set TargetFramework to a Windows-specific target framework moniker, such as net6.0-windows.
    • Add a UI framework property (or both, if necessary):
      • Set UseWPF to true to import and use WPF.
      • Set UseWindowsForms to true to import and use WinForms.
    • (Optional) Set OutputType to WinExe. This produces an app as opposed to a library. To produce a library, omit this property.

    So basically it is how project should be set up to use corresponding components, just add <UseWPF>true</UseWPF> without adding corresponding dlls.

    And UseWPF section:

    The UseWPF property controls whether or not to include references to WPF libraries. This also alters the MSBuild pipeline to correctly process a WPF project and related files. The default value is false. Set the UseWPF property to true to enable WPF support. You can only target the Windows platform when this property is enabled.
    When this property is set to true, .NET 5+ projects will automatically import the .NET Desktop SDK.