wpf 如何在 XAML 中定义和使用变量来定义颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1037477/
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
How can I define and use a variable in XAML to define a color?
提问by Edward Tanguay
I have a number of elements in my XAML which define Foreground="#555"to be the color of faded text in a readonly textbox.
我的 XAML 中有许多元素将Foreground="#555"定义为只读文本框中褪色文本的颜色。
<TextBlock Text="{Binding SingularModelClassFileTitle}" Margin="0 10 0 0"/>
<TextBox Text="{Binding SingularModelClassFileName}"
HorizontalAlignment="Left"
IsReadOnly="True"
Foreground="#555"
Width="500"/>
<TextBox
VerticalScrollBarVisibility="Visible"
AcceptsReturn="True"
Width="500"
Height="100"
IsReadOnly="True"
Foreground="#555"
Text="{Binding SingularModelClassContent}"
HorizontalAlignment="Left"
Margin="0 0 0 20"/>
How can I put this value in a XAML variableand reference in each attribute it so that I only have to change it in one place?
如何将此值放入 XAML 变量并引用它的每个属性,以便我只需在一个地方更改它?
I'm thinking you can do something like this:
我想你可以做这样的事情:
<sys:String x:Key="ReadOnlyTextColor">#555</sys:String>
...
<TextBox Foreground="{StaticResource ReadOnlyTextColor}"/>
And what would be the property xmlns:sys=...
reference for this?
对此的属性xmlns:sys=...
参考是什么?
回答by Matt Hamilton
Try defining your color as a SolidColorBrush:
尝试将您的颜色定义为SolidColorBrush:
<SolidColorBrush x:Key="ReadOnlyTextBrush" Color="#555555" />
...
...
<TextBox Foreground="{StaticResource ReadOnlyTextColor}" />
回答by AlexDrenea
Sometimes you may need to define colors rather than brushes : (one case you would want this is to be able to define Gradients with color parameters) In that case you could just define them like this:
有时您可能需要定义颜色而不是画笔:(一种情况是您希望能够使用颜色参数定义渐变)在这种情况下,您可以像这样定义它们:
<Color x:Key="ButtonColor1">Blue</Color>
<Color x:Key="ButtonColor1">#AABBCC</Color>
<Color x:Key="ButtonColor1" A="0" R="124" G="111" B="44"/>