Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c# - Understanding WPF deriving WIndow class

I'm sure this is easy, but new to me for WPF using C#. I know about inheriting from classes and have done so many times such as in C# WinForms projects...

public class MyClass : DerivedFromClass
{}

However, stumped in WPF and here's the issue. I want to build my own set of controls to be used as a baseline for a new learning project... preset my own styles, colors, backgrounds, and other functionality. No problem. Start first with a WPF Window and create "MyWindow".

Now, I want to take this baseline "MyWindow" and subclass THAT for yet another class of MySubClassedWindow. So, I create a new Window class, and by default, VS2010 builds the both designer and code portions of the form. I do view code on the MySubClassedWindow and find

partial class MySubclassedWindow : Window
{}

In C# using WinForms, I would just change to (and I've included the class library reference that includes the "MyWindow" declaration.

partial class MySubclassedWindow : MyWindow
{}

When I do, I get a compilation error of

Partial declarations of 'MyNameSpace.MySubclassedWindow' must not specify different base classes
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your base class should just be a class file (not a Window).

So create WindowBase.cs

public class WindowBase : Window
{
    // ...
}

In MainWindow (for example) change the xaml.cs file to inherit from WindowBase instead

public partial class MainWindow : WindowBase
{
    public MainWindow()
    {
        InitializeComponent();
    }
    // ...
}

In MainWindow.xaml, include the namespace for WindowBase and change Window to base:WindowBase like this

<base:WindowBase x:Class="SubclassWindow.MainWindow"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                  xmlns:base="clr-namespace:NamespaceForWindowBase"
                  Title="MainWindow" Height="350" Width="525">
    <!--...-->
</base:WindowBase>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...