Home > Enterprise >  How to create a UserControl based on another UserControl?
How to create a UserControl based on another UserControl?

Time:12-12

I created a UserControl called fooControl.

I would like to create another UserControl called fooControlExtended to reuse/add/override both the C# and XAML code that already exists in the base UserControl fooControl.

CodePudding user response:

You can do it this way:

TestUserControl.xaml

<UserControl
    x:Class="UserControls.TestUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:UserControls"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Horizontal">
        <Button
            Click="Button_Click"
            Content="Click" />
        <TextBlock
            x:Name="TextControl"
            Text="TestUserControl" />
    </StackPanel>
</UserControl>

TestUserControl.xaml.cs

using Microsoft.UI.Xaml.Controls;

namespace UserControls;

// You need to remove the "sealed" modifier to allow inheritance.
public /*sealed*/ partial class TestUserControl : UserControl
{
    public TestUserControl()
    {
        this.InitializeComponent();
    }

    protected void UpdateText(string text)
    {
        this.TextControl.Text = text;
    }

    protected virtual void OnButtonClick()
    {
        UpdateText("TestUserControl clicked");
    }

    private void Button_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
    {
        OnButtonClick();
    }
}

TestUserControlEx.cs

namespace UserControls;

public class TestUserControlEx : TestUserControl
{
    protected override void OnButtonClick()
    {
        this.UpdateText("TestUserControlEx clicked.");
    }
}
  • Related