常规使用
代码设置颜色
- 使用Colors的静态属性进行设置
but.Background=new SolidColorBrush(Colors.AliceBlue);
- 使用System.Windows.SystemColors枚举中获取颜色
btn.Background=new SolodColorBrush(SystemColors.ControlColor);
xaml中设置
- 使用颜色名或颜色值
<Lable Background="Red"/> <Lable Background="#ffffff"><!--rrggbb--> <Label Background="#34202020"/><!--aarrggbb aa为Alpha颜色透明度0~255-->
自定义画刷
自定义颜色
- 需要在字典资源中自定义颜色
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Color x:Key="LightRed">#f68484</Color> </ResourceDictionary>
自定义笔刷
普通流程
- 若需需要使用自定义颜色来自定义笔刷,需要进行资源字典的合并
- 在资源字典中自定义笔刷
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:o="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"> <SolidColorBrush o:Freeze="True" x:Key="MyBrush" Color="{DynamicResource LightRed}"></SolidColorBrush> </ResourceDicTionary>
- 引用资源字典,进行使用
<Lable Background="{DynamicResource MyBrush}"/>
自定义渐变笔刷
- 左上角为(0,0),右下角为(1,1),几种颜色分别为起始颜色和终止颜色,Offset为起始点,如下为2中颜色
<LinearGradientBrush o:Freeze="true" x:Key="SideMenuSelectedBrush" StartPoint="0,0" EndPoint="0,1" > <GradientStop o:Freeze="True" Color="{DynamicResource SubTitleColor}" Offset="0"/> <GradientStop o:Freeze="True" Color="#509cd8" Offset="1"/> </LinearGradientBrush> <LinearGradientBrush o:Freeze="true" x:Key="TestBrush" EndPoint="0,1" StartPoint="0,0"> <GradientStop o:Freeze="True" Color="red" Offset="0"/> <GradientStop o:Freeze="True" Color="Black" Offset="0.5"/> <GradientStop o:Freeze="True" Color="Yellow" Offset="0.5"/> <GradientStop o:Freeze="True" Color="Blue" Offset="1"/> </LinearGradientBrush>
-
使用与效果
<Label Background="{DynamicResource TestBrush}"/>
-