Monday, November 18, 2019

WPF .NET Core 3.0 can not add a user control

WPF .NET Core 3.0 can not add a user control
Disclaimer: I loved WPF for Win32. I love UWP for Windows Phones. And I do suspect I will love WPF for .NET Core. So, yesterday I created a test project. And...

At home, I use Visual Studio Community edition. For my pet-projects it's more than enough. I just missed references-based navigation feature which was cut-off from source code editor in community editions if compared with Pro or Enterprise. However, Microsoft applied the feature to each and every edition at Visual Studio 2019, woo-hoo!

So, usual staff: File, New, Project. Visual Studio generates kind of basic project, and this is up to you what to do next. You put a button, a text label, compile and run - viola! It's alive! we have a window with desired controls. Now, let stop the app and try the most frequently used thing at WPF world: user controls, really cool feature that gives you flexible and reusable building blocks for your dream app. Right-click in the Solution Explorer, Add, User Control (WPF)... What?!

I circled through these steps several times before I agreed with the fact: it doesn't work. Visual Studio opens the dialog to specify your class/control name and there is no such option as "User Control" available. Class, Assembly information file, Text template, a bunch of other things, and nothing like "User control". Same issue for app windows: you have one created by WPF project template, and that's all you can have. Bummer news.

Later I tried the same on my work PC, and VS2019 Pro version is perfectly OK on that. User controls are fully-functional, they're created as expected, rendered as expected etc that gives a clue: WPF framework itself is working. Let try to work around the issue until Microsoft published a fix for the IDE.

How to fix Actually, nothing fancy: create an XML file for the XAML part, create a class for C# part. Apply the same naming convention as usual:

  • YourControlName.xaml
  • YourControlName.xaml.cs
Content of the files should be the same idea as you already have in your lonely app window: just replace <Window> tag name with <UserControl>. And do not forget to call InitializeComponent() inside your user control's constructor!

No comments:

Post a Comment