创建您自己的系统颜色
基本上,我如何在静态类或此类中创建自己的一组颜色,以便我可以执行以下操作:
存在什么:
<Setter ... Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
我想要什么:
<Setter ... Value="{DynamicResource {x:Static MyColors.Color1}}"/>
Basically, how can I create my own set of Colors in a static class or the such so that I can do something like this:
What exists:
<Setter ... Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
What I want:
<Setter ... Value="{DynamicResource {x:Static MyColors.Color1}}"/>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
资源键可以是任何内容,因此您可以同时使用
Color
作为键和值:静态构造函数使用自身作为应用程序资源的键来添加颜色。
(
SystemColors
在内部为每个定义的颜色或画笔使用SystemResourceKeys
,但是您无权访问该类(这是有道理的),或者您可以子类ResourceKey
如果您对使用该值作为自己的键有疑问)您可以像这样使用它:
如果您需要在本地级别覆盖该键,您也可以这样做:
编辑:如果你有很多颜色、画笔等,你也可以使用反射在构造函数中注册资源(我使用字段,如果你使用属性来公开数据,你需要稍微调整一下) :
Resource Keys can be anything, so you can use a
Color
as a key and value at the same time:The static constructor adds the colour using itself as a key to the application resources.
(
SystemColors
usesSystemResourceKeys
internally for every defined colour or brush, you have no access to that class however (which makes sense), alternatively you could subclassResourceKey
if you take issue with using the value as its own key)You can use it like this:
And if you need to override the key on a local level you can do so as well:
Edit: If you have lots of colours, brushes and whatnot you could also use reflection to do the resource registering in the constructor (i used fields, if you use properties to expose the data you need to adjust this slightly):
我想我应该提出另一个选择。您可以通过执行类似以下操作来使用静态资源...
然后在您的 XAML 中使用:
我刚刚花了 10 分钟尝试让它与 DynamicResource 扩展一起使用,但我做不到。如果有人知道如何(或为什么),请告诉我们:)
thought I'd chime in with another option. You can use a Static resource instead by doing something like the following...
Then in your XAML, use:
I've just spent 10 minutes trying to get it to work with a DynamicResource extension, but I can't do it. If anyone knows how (or why) then let us know :)
您可以轻松做到这一点。您必须定义以下类:
例如在您的
App.xaml
中:由于静态字符串实际上只是用于强类型,所以我通常不会创建这样的静态类,而只是使用任何内容我定义的键因此变为:(
我相信您也可以使用
#FF969696
中的强类型但我现在不确定...)(还要注意的是,使用
x:Static
时,您必须指定 MyColors 所在的命名空间,这样它就变成了{x:Static local :MyColors.Color1}
)You can easily do this. You have to define the following class:
and for example in your
App.xaml
you do:as the static string is actually just for strong typing I usually don't create such a static class and just use whatever key I defined so this becomes:
(I believe you can also use the strong typing in
<Color x:Key="{x:Static MyColors.Color1}">#FF969696</Color>
but I'm not sure right now...)(also beware of that for using
x:Static
you will have to specify the namespace where MyColors sits so this becomes{x:Static local:MyColors.Color1}
)