Custom Entry Points in WPF on .NET Core
Posted: January 31, 2020 Filed under: .NET, .NET Core, WPF | Tags: .NET, .NET Core, WPF 2 CommentsTo create a custom entry point for a WPF application that is created using the default template in Visual Studio and targets the .NET Framework, you can change the Build Action
property of the App.xaml
file from ApplicationDefinition
to Page
and create a class with a static Main
method. That’s what I did in a previous post about handling protocol activation and redirection in packaged apps.
If you target .NET Core and try to do the same thing in Visual Studio 2019, you will get a dialog saying “Property is not valid” and some build errors that complains about duplicate ‘Compile’ and ‘Page’ items being included.
What you should do instead of changing the Build Action
is to edit the .csproj
project file (Project->Edit Project File in Visual Studio) and include a <StartupObject>
element:
<PropertyGroup> <OutputType>WinExe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> <UseWPF>true</UseWPF> <StartupObject>WpfCoreApp1.Program</StartupObject> </PropertyGroup>
The value of the element refers to the fully qualified named of the class where the custom Main
method is implemented:
namespace WpfCoreApp1 { class Program { [STAThread] static void Main() { App application = new App(); application.InitializeComponent(); application.Run(); } } }
The above implementation of the Main
method is roughly the same as the one that is generated for you by the compiler if you don’t change anything after creating a new project in Visual Studio using the WPF App (.NET Core)
template. If you put a breakpoint in it and start debugging, it should get hit when the application starts. You don’t need to do anything additional with the auto-generated App.xaml
and App.xaml.cs
files, i.e. you can add application-wide resources and implement custom startup logic in these files as usual.
Hi, can you update the new link of the sample code of this article, the original link is invalid.I will be very appreciate,thank you.
https://blog.magnusmontin.net/2013/09/29/export-data-from-a-datagrid/#comments
Hi hongjiapeng ,
The link has now been updated.