UWP 继承自我的用户控件

UWP inherit from my Usercontrol

我正在尝试创建一个 ModalPage class,它 运行 很好,但我想创建 4 个子class 来专门化我的 ModalPage.

我的 ModalPage 继承自 UserControl (XAML + C#)。在继承自 ModalPage 的 sub-classes 上,我必须参数化特定的内容和标题。

我想,最好的方法是像 ContentDialog class 一样,有一个带有 ContentDialog1 : ContentDialog 的 c# class 和一个 XAML 页面:

<ContentDialog>
    <Grid>
    </Grid>
</ContentDialog>

但我无法继承我的 UserControl,因为它使用 XAML。我应该创建自定义控件(继承自 Control)而不是 UserControl 吗?

If I expose dependency property to set the value of content in my userControl, the content can be another UserControl?

是的,我们可以使用 ContentPresenter 来实现它。以下是一个简单示例:

在XAML中:

<UserControl x:Class="UWP.ModalPage"
             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:UWP"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             d:DesignHeight="300"
             d:DesignWidth="400"
             mc:Ignorable="d">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ContentPresenter x:Name="Title"
                          HorizontalAlignment="Center"
                          HorizontalContentAlignment="Center"
                          Content="{x:Bind ModalTitle}" />
        <ContentPresenter x:Name="Content" Grid.Row="1" Content="{x:Bind ModalContent}" />
    </Grid>
</UserControl>

在代码隐藏中:

public sealed partial class ModalPage : UserControl
{
    public ModalPage()
    {
        this.InitializeComponent();
    }

    public static readonly DependencyProperty ModalTitleProperty = DependencyProperty.Register("ModalTitle", typeof(object), typeof(ModalPage), new PropertyMetadata(null));

    public object ModalTitle
    {
        get { return GetValue(ModalTitleProperty); }
        set { SetValue(ModalTitleProperty, value); }
    }

    public static readonly DependencyProperty ModalContentProperty = DependencyProperty.Register("ModalContent", typeof(object), typeof(ModalPage), new PropertyMetadata(null));

    public object ModalContent
    {
        get { return GetValue(ModalContentProperty); }
        set { SetValue(ModalContentProperty, value); }
    }
}

然后我们可以在如下页面中使用此 ModalPage

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <local:ModalPage ModalTitle="TITLE">
        <local:ModalPage.ModalContent>
            <local:MyUserControl />
        </local:ModalPage.ModalContent>
    </local:ModalPage>
</Grid>