[英]Why does style TargetType="Window" not work when set from App.xaml?
I'm creating a simple WPF project in VS2013 and I want to apply properties to my main Window.我正在 VS2013 中创建一个简单的 WPF 项目,我想将属性应用于我的主要 Window。 I set them in my
App.xaml
file like this:我将它们设置在我的
App.xaml
文件中,如下所示:
<Application.Resources>
<Style TargetType="Window">
<Setter Property="Background" Value="#FF2D2D30" />
</Style>
</Application.Resources>
The problem is that nothing happens.问题是什么都没有发生。 When I change the
TargetType
to Grid however, the setter property works just fine.然而,当我将
TargetType
更改为 Grid 时,setter 属性工作得很好。 Why does this happen?为什么会这样?
It is necessary to add construction in Window
: 有必要在
Window
添加构造:
Style="{StaticResource {x:Type Window}}"
Window
in XAML: XAML中的
Window
:
<Window x:Class="WindowStyleHelp.MainWindow"
Style="{StaticResource {x:Type Window}}"
...>
Or define Style
in resources like this: 或者在资源中定义
Style
,如下所示:
xmlns:local="clr-namespace:MyWpfApplication"
<Application.Resources>
<Style TargetType="{x:Type local:MainWindow}">
<Setter Property="Background" Value="#FF2D2D30"/>
</Style>
</Application.Resources>
Answering for this question "Why does it not works". 回答这个问题“为什么它不起作用”。
The reason why the Target type is not applied to your Window is because, you are using a derived type of a window with name "MainWindow". Target类型未应用于Window的原因是,您使用的是名为“MainWindow”的窗口的派生类型。 So in your style resource you have to set the target type as the derived type (MainWindow).
因此,在您的样式资源中,您必须将目标类型设置为派生类型(MainWindow)。 By doing so it will be applied only to the "MainWindow" window.
通过这样做,它将仅应用于“MainWindow”窗口。
<Style TargetType="local:MainWindow">
<Setter Property="Background" Value="#FF2D2D30" />
</Style>
You can either set the TargetType to "MainWindow" or set resource reference for Style property.您可以将 TargetType 设置为“MainWindow”或为 Style 属性设置资源引用。
public MainWindow()
{
InitializeComponent();
SetResourceReference(StyleProperty, typeof(Window));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.