为什么样式TargetType=“Window”在从App.xaml设置时不起作用?

pcrecxhr  于 2022-12-07  发布在  其他
关注(0)|答案(3)|浏览(129)

我在VS2013中创建了一个简单的WPF项目,我想将属性应用到我的主窗口。我在我的App.xaml文件中设置了这些属性,如下所示:

<Application.Resources>
    <Style TargetType="Window">
        <Setter Property="Background" Value="#FF2D2D30" />
    </Style>
</Application.Resources>

问题是什么都没有发生。当我把TargetType改为Grid时,setter属性工作得很好。为什么会发生这种情况?

nx7onnlm

nx7onnlm1#

It is necessary to add construction in Window :

Style="{StaticResource {x:Type Window}}"

Window in XAML:

<Window x:Class="WindowStyleHelp.MainWindow"
        Style="{StaticResource {x:Type Window}}"
        ...>

Or define Style in resources like this:

xmlns:local="clr-namespace:MyWpfApplication"

<Application.Resources>
    <Style TargetType="{x:Type local:MainWindow}">
        <Setter Property="Background" Value="#FF2D2D30"/>
    </Style>
</Application.Resources>
wbgh16ku

wbgh16ku2#

回答这个问题“为什么它不工作”。
目标类型未应用于您的窗口的原因是,您使用的是名为“MainWindow”的窗口的派生类型。因此,在样式资源中,您必须将目标类型设置为派生类型(MainWindow)。这样,它将仅应用于“MainWindow”窗口。

<Style  TargetType="local:MainWindow">
    <Setter Property="Background" Value="#FF2D2D30" />
</Style>
ckocjqey

ckocjqey3#

可以将TargetType设置为"MainWindow",也可以设置Style属性的资源引用。

public MainWindow()
{
    InitializeComponent();
    SetResourceReference(StyleProperty, typeof(Window));
}

相关问题