为什么窗口背景的样式设置没有效果?

11

这是 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>

我也有MainWindow.xaml。 在VS的设计模式下查看时,背景确实是灰色的,就像应该的一样。 但是,在应用程序运行时,窗口的背景是默认的白色。

为什么会这样呢?

如何修复这个问题? 我想让所有窗口默认具有标准背景。

2个回答

20
问题在于运行时,您的窗口类型将是MainWindow而不是Window。隐式样式不适用于TargetType的派生类型。因此,您的样式将不会被应用。
在设计时,您正在设计MainWindow,但我怀疑它创建了一个Window作为基础。
您需要更改类型以匹配您窗口的类型。

谢谢!它在设计视图中工作的事实令人困惑。 - Mikhail Orlov

15

在跟进来自CodeNaked的答案后,你需要为每个Window创建一个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

谢谢!即使是 <Window.Resources><Style BasedOn="{StaticResource {x:Type Window}}" TargetType="{x:Type local:MainWindow}"/> </Window.Resources> 也可以。 - Mikhail Orlov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接