如何为 xaml 控件创建一个公共超类?

How to have a common superclass for xaml controls?

我有一个我继承的 xaml / uwp 应用程序。

最初的开发者创建了许多扩展 UserControl 的控件。有一些代码是所有这些 class 的通用代码,他将这些代码复制并粘贴到每个 class 中。我想重构一些东西,使通用代码在 superclass.

我创建了 superclass,但它不起作用:编译器声称 "partial declarations of must not specify different base classes".

我不知道我应该怎么做才能解决这个问题。在 xaml 文件中,指定了 x:Class 属性,它具有所需 class 的全名。我尝试将根元素从 UserControl 更改为我的 class 的名称(具有完整的命名空间),但这也不起作用。

这有什么诀窍?我敢肯定,Microsoft 并没有打算 xaml 来阻止我们创建 class 层次结构。

谢谢, 弗兰克

How to have a common superclass for xaml controls?

根据您的要求,您可以为 UserControl 创建抽象基础 class。关键过程是将基础 class 命名空间添加到 xaml 中。

例如:

namespace ButtonResourceTest
{
    public sealed partial class CustomUserControl : UserControlBase
    {
        public CustomUserControl()
        {
            this.InitializeComponent();
        }
    }
    public  abstract class UserControlBase : UserControl
    {


    }


}

Xaml

修改默认的UserControl根节点为local:UserControlBase.

<local:UserControlBase
    x:Class="ButtonResourceTest.CustomUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ButtonResourceTest"
    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>

    </Grid>
</local:UserControlBase>