在WPF中对派生类型的所有实例进行样式化



我有一个名为MyWindow的类,它派生自Window:

using System.Windows;
public class MyWindow : Window
{
}

我在MainWindow.xaml中使用这个类:

<MyWpfApp:MyWindow x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfApplication1="clr-namespace:WpfApplication1"
          Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Text="Test" Foreground="Orange"/>
    </Grid>
</MyWpfApp:MyWindow>

App.xaml文件中,我添加了以下样式来覆盖所有MyWindow实例的Background属性:

<Application.Resources>
    <Style TargetType="MyWpfApp:MyWindow">
        <Setter Property="Background" Value="Black"></Setter>
    </Style>
</Application.Resources>

但是这并没有改变任何东西。MainWindow没有样式

我应该怎么做,这样我就可以使用全局样式的所有MyWindow s?

注:我检查了"Modern UI"的代码,我看到他们在窗口的构造函数中应用了如下内容:

using System.Windows;
public class MyWindow : Window
{
    public MyWindow()
    {
        DefaultSyleKey = typeof (MyWindow);
    }
}

但是如果我这样做,主窗口的内容区域最终会完全变黑。我猜它的Template属性以某种方式被覆盖,但我不明白如何,以及如何使这项工作。

好的,我算出来了。显然,有一个特殊的文件可以使用,名为generic.xaml

您需要在那里添加您的样式定义,然后将该文件添加到名为Themes的目录。

WPF最终将使用它作为回退:Themesgeneric.xaml

最新更新