为什么窗口背景的样式设置不起作用?

Mik*_*lov 11 wpf xaml app.xaml

这是App.xaml:

<Application>
<Application.Resources>
    <ResourceDictionary>
        <Style TargetType="Window">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
        </Style>
    </ResourceDictionary>
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)

我也有MainWindow.xaml.在VS中的设计模式下查看时,它的背景确实是灰色的,应该是它.无论如何,当应用程序运行时,窗口的背景默认为白色.

为什么?

如何解决这个问题?我希望所有窗口默认都具有标准背景.

Cod*_*ked 18

问题是在运行时,窗口的类型将是MainWindow,而不是Window.隐式样式不适用于TargetType的派生类型.所以你的风格不适用.

在设计期间,你正在设计你的MainWindow,但我怀疑它创造了一个Window基础.

您需要更改类型以匹配窗口的类型.


Fre*_*lad 12

从答案跟进CodeNaked,你必须创建一个Style为每个Window你有,但你可以使用相同的样式为所有的人都用BasedOn这样的

<Application.Resources>
    <ResourceDictionary>
        <Style TargetType="Window">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
        </Style>
        <Style TargetType="{x:Type local:MainWindow}"
               BasedOn="{StaticResource {x:Type Window}}"/>
        <Style TargetType="{x:Type local:SomeOtherWindow}"
               BasedOn="{StaticResource {x:Type Window}}"/>
        <!-- Add more Windows here... -->
    </ResourceDictionary>
</Application.Resources
Run Code Online (Sandbox Code Playgroud)