wpf 使用资源设置窗口背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2101821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:26:20  来源:igfitidea点击:

Setting Window background color using resource

wpfresourcescolorsbackgroundwindow

提问by David Veeneman

I need to use a resource to set the color of the main window in my WPF application. Since the resource declaration comes after the window declaration (I am importing a resource dictionary), I can't use a Backgroundproperty in the Windowobject. So, I thought I would set the background this way:

我需要使用资源来设置 WPF 应用程序中主窗口的颜色。由于资源声明在窗口声明之后(我正在导入资源字典),因此我无法BackgroundWindow对象中使用属性。所以,我想我会这样设置背景:

<Window.Resources>
...
</Window.Resources>

<Window.Background>
    <SolidColorBrush Color="{StaticResource WindowBackgroundBrush}"  />
</Window.Background>

My syntax is a bit off, since the object won't take a brush resource for its Color property. What's the fix? Thanks for your help.

我的语法有点不对,因为对象不会为其 Color 属性获取画笔资源。有什么解决办法?谢谢你的帮助。

回答by Muad'Dib

this works:

这有效:

<Window x:Class="Moria.Net.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        x:Name="window"
        Background="{DynamicResource WindowBrush}"
        Width="800" Height="600">
    <Window.Resources>
        <SolidColorBrush x:Key="WindowBrush" Color="LightGray"/>
    </Window.Resources>
</Window>

the main thing to note here is the x:name in the window, and the DynamicResource in the Background property

这里要注意的主要是窗口中的 x:name 和 Background 属性中的 DynamicResource

alternativly, this works as well....

或者,这也有效......

  <Window.Resources>
        <SolidColorBrush x:Key="WindowBrush" Color="LightGray"/>
    </Window.Resources>
    <Window.Style>
        <Style TargetType="{x:Type Window}">
            <Setter Property="Background" Value="{StaticResource WindowBrush}"/>
        </Style>
    </Window.Style>

As a side note, if you want to use theming for you application, you should look into component resource keys

作为旁注,如果你想为你的应用程序使用主题,你应该查看组件资源键

回答by Tom Dudfield

Try this

尝试这个

<Window.Background>
    <StaticResource ResourceKey="WindowBackgroundBrush" />
</Window.Background>

回答by Jakob Christensen

The solution is to put your resources in App.xaml instead. That way you can set the Background on your Window without any problems.

解决方案是将您的资源放在 App.xaml 中。这样您就可以毫无问题地在窗口上设置背景。