【发布时间】:2023-03-26 06:09:01
【问题描述】:
我有一个在 2 个应用程序之间应该相同的窗口,除了某些点。 我想从它继承来创建一个子类(没有 XAML),它只在构造函数中进行一些自定义(如窗口的标题)。
这可能吗?
【问题讨论】:
-
你试过了吗? ;)
-
为什么不通用风格?
标签: wpf xaml inheritance
我有一个在 2 个应用程序之间应该相同的窗口,除了某些点。 我想从它继承来创建一个子类(没有 XAML),它只在构造函数中进行一些自定义(如窗口的标题)。
这可能吗?
【问题讨论】:
标签: wpf xaml inheritance
这可能吗?
是的。
创建一个继承自System.Windows.Window的类:
public class YourBaseClass : Window
{
public YourBaseClass() : base()
{
Title = "Common Title";
}
}
...并在代码隐藏中更改您的窗口的基类以使用这个基类:
public partial class MainWindow : YourBaseClass
{
public MainWindow()
{
InitializeComponent();
}
}
...在 XAML 中:
<local:YourBaseClass x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Height="300" Width="300">
</local:YourBaseClass>
【讨论】:
与窗口窗体不同,WPF 没有视觉继承。原因可以参考这个post。
因此,我们不能在这里使用继承。但是,您可以将自定义属性添加到您的 windows 类并根据该属性进行自定义。
假设我想创建两个具有不同“标题”的相似窗口(这只是一个示例,我知道窗口有一个 Title 属性):
在 xaml.cs 中:
public WindowTest //constructor
{
InitializeComponent();
this.Loaded+=WindowTest_Loaded;
}
private void WindowTest_Loaded(object sender, RoutedEventArgs e)
{
//Please note that custom property wont be set until Windows is loaded.
//Your customization here
this.Title = TitleText;
}
public string TitleText
{
get { return GetValue( Property1Property ).ToString(); }
set { SetValue( TitleTextProperty, value ); }
}
// Using a DependencyProperty as the backing store for Property1.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty TitleTextProperty
= DependencyProperty.Register(
"TitleText",
typeof( string ),
typeof( WindowTest ),
new PropertyMetadata( String.Empty )
);
在xml中
<Grid>
<test:WindowText TitleText = "Hello World"/> //first window
<test:WindowText TitleText = "I Hate You"/> //second window
</Grid>
【讨论】: