简体   繁体   English

使用 DynamicResource 如何“神奇地”将画笔转换为颜色?

[英]How does using DynamicResource 'magically' convert a brush to a color?

I have defined some brush resources in terms of system colors like the following:我在系统 colors 方面定义了一些画笔资源,如下所示:

<SolidColorBrush 
   x:Key="brushKey1" 
   Color="{x:Static SystemColors.ControlColor}" 
   />

(This is done because some third-party code expects to find brushKey1 defined). (这样做是因为一些第三方代码希望找到定义的brushKey1 )。

But I noticed that the following also compiles and appears to work:但我注意到以下内容也可以编译并且似乎可以工作:

<SolidColorBrush 
   x:Key="brushKey1" 
   Color="{DynamicResource {x:Static SystemColors.ControlBrush}}" 
   />

The first one uses a COLOR object, but the second uses a BRUSH.第一个使用 COLOR object,但第二个使用 BRUSH。

Why does this work?为什么这行得通? Is DynamicResource automatically figuring out how to do some sort of cast or conversion? DynamicResource是否会自动计算出如何进行某种类型的转换或转换?

Note that this does not work:请注意,这不起作用:

<SolidColorBrush 
   x:Key="brushKey1" 
   Color="{x:Static SystemColors.ControlBrush}" 
   />

This line will compile but throws a runtime exception.此行将编译但会引发运行时异常。

There is no magic or conversion.没有魔法或转换。 Take a look to the Resources , there must be an entry with a SystemColors.ControlBrush object as key.查看Resources ,必须有一个以SystemColors.ControlBrush object 作为键的条目。

So in case所以万一

<SolidColorBrush x:Key="brushKey1"  Color="{DynamicResource {x:Static SystemColors.ControlBrush}}"/>

you get "value" of an entry from ResourceDictionary .您从ResourceDictionary获得条目的“价值”。

in another case在另一种情况下

<SolidColorBrush x:Key="brushKey1"  Color="{x:Static SystemColors.ControlBrush}"/>

you try to assign the object, which being used as "key" in ResourceDictionary .您尝试分配 object,它在ResourceDictionary中用作“键”。

Compiles?编译? Yes.是的。 Your brushKey1 references a resource with an x:Key of {x:Static SystemColors.ControlBrush} using the DynamicResource markup extension.您的brushKey1使用DynamicResource标记扩展引用了一个x:Key{x:Static SystemColors.ControlBrush}的资源。 You could set the key to anything.你可以设置任何东西的钥匙。 It would still compile.它仍然会编译。

Works?作品? No, not unless you have defined a Color resource with an x:Key of {x:Static SystemColors.ControlBrush} :不,除非您使用{x:Static SystemColors.ControlBrush}x:Key定义了Color资源:

<Color x:Key="{x:Static SystemColors.ControlBrush}">Red</Color>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM