[英]How to create a UserControl based on another UserControl?
I created a UserControl called fooControl .我创建了一个名为fooControl的 UserControl。
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 .我想创建另一个名为fooControlExtended的 UserControl 以重用/添加/覆盖基本 UserControl fooControl中已存在的 C# 和 XAML 代码。
You can do it this way:你可以这样做:
TestUserControl.xaml 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 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测试用户控件Ex.cs
namespace UserControls;
public class TestUserControlEx : TestUserControl
{
protected override void OnButtonClick()
{
this.UpdateText("TestUserControlEx clicked.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.