XAML 如何基于另一个UserControl创建一个UserControl?

8fsztsew  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(169)

我创建了一个名为 fooControl 的用户控件。
我想创建另一个名为 fooControlExtended 的UserControl,以重用/添加/覆盖基本UserControl fooControl 中已经存在的C#和XAML代码。

hjqgdpho

hjqgdpho1#

您可以这样做:

测试用户控件.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>

测试用户控件.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();
    }
}

测试用户控件示例.cs

namespace UserControls;

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

相关问题