UWP继承自我的Usercontrol

时间:2016-05-02 13:16:01

标签: c# xaml user-controls uwp contentpresenter

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

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

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

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

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

1 个答案:

答案 0 :(得分:3)

  

如果我公开依赖属性来设置我的userControl中的内容值,那么内容可以是另一个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>