Home > Net >  How to use Xaml inheritance in WinUI 3?
How to use Xaml inheritance in WinUI 3?

Time:11-11

Judging from answers like this it looks like xaml inheritance works for WPF and UWP.

Does it work for WinUI 3?

Using code like this:

    <local:YourBaseClass x:Class="MyApp.ChildClass"
        ...
        xmlns:local="clr-namespace:MyApp">
    </local:YourBaseClass>

I get the error:

Error WMC0001 Unknown type 'YourBaseClass' in XML namespace 'clr-namespace:MyApp'

CodePudding user response:

Does it work for WinUI 3?

Yes. It almost exactly the same.

  1. Create the base class that inherits from Microsoft.UI.Xaml.Window:

     public class YourBaseClass : Microsoft.UI.Xaml.Window
     {
         public YourBaseClass() : base()
         {
             Title = "Title...";
         }
     }
    
  2. Modify MainWindow.xaml.cs to inherit from the new base class:

     public sealed partial class MainWindow : YourBaseClass
     {
         public MainWindow()
         {
             this.InitializeComponent();
         }
    
         private void myButton_Click(object sender, RoutedEventArgs e)
         {
             myButton.Content = "Clicked";
         }
     }
    
  3. Modify the root element in MainWindow.xaml:

     <local:YourBaseClass
         x:Class="WinUI3App.MainWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="using:WinUI3App"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d">
    
         <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
             <Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
         </StackPanel>
     </local:YourBaseClass>
    
  • Related