如何为wpf窗口的背景颜色定义静态资源? [英] How to define static resource for background color of wpf window?

查看:93
本文介绍了如何为wpf窗口的背景颜色定义静态资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我在window.resource中编写LinearGradientBrush代码,如下所示

  <   Window.Resources  >  
< LinearGradientBrush x:密钥 = cbColor >
< GradientStop 偏移量 = 0 < span class =code-attribute> 颜色 = 红色 > < / GradientStop >
< GradientStop Offset = 0.5 颜色 = > < / GradientStop >
< GradientStop 偏移量 = 1 颜色 = 绿色 > < / GradientStop >

< / LinearGradientBrush >

< /Window.Resources >



并将其作为背景使用窗口作为一个静态资源,但它给出了一些错误。

如果我使用它作为一个动态资源它工作正常,我很困惑为什么它不使用静态资源,因为我只写它在窗口xaml代码



我尝试过:



i试图使用静态资源标记

解决方案

对StackOverflow上的问题有一个很好的解释:

c# - ResourceDictionary的Windows样式不适用 - 堆栈溢出 [ ^ ]



基本上,窗口是在嵌套<$ c $之前创建的c> ResourceDictionary 已处理完毕。此时,< Window.Resources> 字典中没有定义任何内容。



如果使用 StaticResource ,设计器将失败,应用程序将崩溃。



如果您使用 DynamicResource ,最初将创建窗口而不应用资源;一旦处理了嵌套的 ResourceDictionary ,并且其资源可用,窗口样式将会更新。



更好的解决方案是将资源移动到< Application.Resources> 字典,在创建窗口之前 处理。

hi all,
im writing LinearGradientBrush code in window.resource like below

<Window.Resources>
 <LinearGradientBrush x:Key="cbColor">
           <GradientStop Offset="0" Color="Red"></GradientStop>
           <GradientStop Offset="0.5" Color="Silver"></GradientStop>
           <GradientStop Offset="1" Color="Green"></GradientStop>

 </LinearGradientBrush>

   </Window.Resources>


and using this as a background of window as a static resource but it is giving some error.
and if am using it as a dynamic resource it working fine,im confused why it is not working with static resource as i am writing it only in window xaml code

What I have tried:

i tried to write in window.resource with static resource tag

解决方案

There's a good explanation of the problem on StackOverflow:
c# - Windows Style from ResourceDictionary don't apply - Stack Overflow[^]

Basically, the Window is created before the nested ResourceDictionary is processed. At that point, nothing defined in the <Window.Resources> dictionary is available.

If you use a StaticResource, the designer will fail and the application will crash.

If you use a DynamicResource, the window will initially be created without the resource being applied; once the nested ResourceDictionary has been processed, and its resources are available, the window style will be updated.

A better solution is to move your resources to the <Application.Resources> dictionary, which is processed before the window is created.


这篇关于如何为wpf窗口的背景颜色定义静态资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆