Warm tip: This article is reproduced from stackoverflow.com, please click
uwp-xaml xaml

How to have a common superclass for xaml controls?

发布于 2020-04-13 10:47:04

I have a xaml / uwp application which I inherited.

The original developer created a number of controls that extend UserControl. There is some code that is common to all of these classes which he copied and pasted into each class. I want to refactor things such that the common code is in a superclass.

I created the superclass, but it doesn't work: the compiler claims that "partial declarations of must not specify different base classes".

I don't know what I'm supposed to do to fix this. In the xaml file, the x:Class attribute is specified and it has the full name of the desired class. I tried changing the root element from UserControl to the name of my class (with the complete namespace) but this doesn't work either.

What's the trick to this? I'm sure that Microsoft didn't intend for xaml to prevent us from creating class hierarchies.

Thanks, Frank

Questioner
Frank LaRosa
Viewed
19
Nico Zhu - MSFT 2020-02-04 11:43

How to have a common superclass for xaml controls?

For your requirement, you could make abstract base class for UserControl. And the key procedure is add the base class namesapce into the xaml.

For example:

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


    }


}

Xaml

modify the default UserControl root node to 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>