了解 WPF 派生 WINdow 类 [英] Understanding WPF deriving WIndow class
问题描述
我确信这很容易,但对我来说使用 C# 的 WPF 是新手.我知道从类继承并且已经做了很多次,例如在 C# WinForms 项目中...
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
{}
但是,在 WPF 中难住了,这就是问题所在.我想构建我自己的一组控件,用作新学习项目的基线……预设我自己的样式、颜色、背景和其他功能.没问题.首先从 WPF 窗口开始并创建MyWindow".
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".
现在,我想采用此基线MyWindow"并将其子类化为另一类 MySubClassedWindow.因此,我创建了一个新的 Window 类,默认情况下,VS2010 构建表单的设计器和代码部分.我确实在 MySubClassedWindow 上查看代码并找到
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
{}
在使用 WinForms 的 C# 中,我将更改为(并且我已经包含了包含MyWindow"声明的类库引用.
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
推荐答案
你的基类应该只是一个类文件(而不是一个 Window
).
Your base class should just be a class file (not a Window
).
所以创建WindowBase.cs
So create WindowBase.cs
public class WindowBase : Window
{
// ...
}
在 MainWindow 中(例如)将 xaml.cs 文件改为从 WindowBase 继承
In MainWindow (for example) change the xaml.cs file to inherit from WindowBase instead
public partial class MainWindow : WindowBase
{
public MainWindow()
{
InitializeComponent();
}
// ...
}
在 MainWindow.xaml 中,包含 WindowBase 的命名空间并将 Window 更改为 base:WindowBase 像这样
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>
这篇关于了解 WPF 派生 WINdow 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!