Why does style TargetType=“Window” not work when set from App.xaml?

北战南征 提交于 2019-12-23 09:49:59

问题


I'm creating a simple WPF project in VS2013 and I want to apply properties to my main Window. I set them in my App.xaml file like this:

<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. Why does this happen?


回答1:


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>



回答2:


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". So in your style resource you have to set the target type as the derived type (MainWindow). By doing so it will be applied only to the "MainWindow" window.

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


来源:https://stackoverflow.com/questions/22269709/why-does-style-targettype-window-not-work-when-set-from-app-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!