开发者

How to implement common part for user control with inheritage?

开发者 https://www.devze.com 2023-01-26 07:13 出处:网络
I have some common parts for all user control. It\'s defined in an interface, say MyInterface. Then I implement part of it in a class, say MyBaseClass:

I have some common parts for all user control. It's defined in an interface, say MyInterface.

Then I implement part of it in a class, say MyBaseClass:

class MyBaseClass : MyInterface    
{    
//......    
}

Then when I create a user control, I want to this user control has the implementation of the common part. So I want to change code behind for MyControl as:

public partial class MyControl : UserControl, MyBaseClass
    {
        public MyControl()
        {
            InitializeComponent();
        }
    }

but system will give me error. reason: Mybase is not partial class. if change MyBaseClass as partial, still get erro say something like "not allow mutiple base class".

One solution is like

public partial class MyUserControl : UserControl, MyInterface
    {
        public MyU开发者_运维问答serControl ()
        {
            InitializeComponent();
        }
    }

but this will cause duplicate implementation for each user control. Many copy & paste. I don't want to this way.

Tried following way:

public class MyBaseClass : UserControl, MyInterface

or

public partial class MyBaseClass : UserControl, MyInterface

I got error: Partial declarations of 'MyUserControl' must not specify different base classes

How to resove this problem?


I suggest you go with this:-

public class MyBaseClass : UserControl, MyInterface 

Which you've tried but there is a twist. When you then wnat to create a derived "UserControl" from this, start with a standard Usercontrol but then change the code-behind file to this:-

public partial class MyDerivedClass : MyBaseClass

and

change the Xaml to:-

<local:MyBaseClass x:Class="MyNamespace.MyDerivedClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyNamespace"
>
    <Grid x:Name="LayoutRoot" Background="White">
    </Grid>
</local:MyBaseClass>
0

精彩评论

暂无评论...
验证码 换一张
取 消