如何在 XAML 代码中创建支持其中其他元素的 UserControl

How to create UserControl which support other element inside it in XAML code

我想在我的 UserControl 中插入其他 FrameworkElements,但如果我在 XAML 代码中这样做,控件将无法正常工作。 (我需要制作 Panel/Grid 类型 control)。换句话说,它失去了 contents。如何解决这个问题呢?我找到了一些示例,但这些示例在 UWP 中不起作用。我想让下面的示例非常简单,以说明我的意思和需要。

XAML

<!--THE CONTROL-->
<local:TestControl Width="300" Height="300">
    <!--LIKE TO ADD THIS ONE INSIDE THE CONTROL-->
    <TextBlock Text="Some Text"></TextBlock>
</local:TestControl>

XAML 控制

<UserControl
    x:Class="MyApp.TestControl"
    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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"

    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid Background="DarkGray" BorderBrush="Black" BorderThickness="2" CornerRadius="10"></Grid>
</UserControl>

代码隐藏

namespace MyApp
{
    public sealed partial class TestControl : UserControl
    {
        public TestControl()
        {
            this.InitializeComponent();
        }
    }
}

用模板化控件替换 UserControl

  1. 创建一个名为 TestControl 的 class 继承自 ContentControl:

    public sealed class TestControl : ContentControl
    {
        public TestControl() => DefaultStyleKey = typeof(TestControl);
    }
    
  2. 在您的项目中创建一个 themes 文件夹,并向该文件夹添加一个名为 generic.xamlResourceDictinonarythemes/generic.xaml 名称对于框架能够找到它很重要。在此文件中,您为控件定义一个模板:

    <Style TargetType="local:TestControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:TestControl">
                    <Grid Background="DarkGray" BorderBrush="Black" BorderThickness="2" CornerRadius="10">
                        <ContentPresenter />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
  3. 像以前一样创建控件实例:

    <local:TestControl Width="300" Height="300">
        <!--LIKE TO ADD THIS ONE INSIDE THE CONTROL-->
        <TextBlock Text="Some Text"></TextBlock>
    </local:TestControl>
    

TextBlock 将在 ContentPresenter 元素在 ControlTemplate 中的位置结束。

请参阅@Jerry Nixon 的 MSDN Magazine article 了解有关如何创建自定义控件的更多信息。