如何将颜色设置为在整个应用程序中使用的静态资源?

时间:2020-05-19 15:24:51

标签: wpf xaml

我在整个应用程序中都有这样的按钮:

<Button Content="Click me" Background="#7AC040" />

我什至设置了一些静态资源来设置表格列标题的样式:

<Style x:Key="TableHeadersStyle" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Background" Value="#7AC040" />
    ...
</Style>

现在您可以看到,我一直在对各种组件的颜色进行硬编码。但是,由于应用程序越来越大,我想将这些颜色“提取”到某种静态资源“变量”中,以代替那些十六进制值。我有办法吗?

也许是这样的:

<Application.Resources>
    <ResourceDictionary>
        <Color x:Key="CompanyColor">#NewColorHEX</Color>
    </ResourceDictionary>
</Application.Resources>

... 

<Button Content="Click me" Background="{StaticResource CompanyColor}" />

....

<Style x:Key="TableHeadersStyle" BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Background" Value="{StaticResource CompanyColor}" />
    ...
</Style>

很明显,以上方法不起作用,但是我有办法吗?

1 个答案:

答案 0 :(得分:2)

您应将资源定义为int end = name.length; while(end > 0 && name[end - 1] == 0) end--; String nameStr = new String(name, 0, end, StandardCharsets.US_ASCII);

Brush

然后可以使用它来设置任何<SolidColorBrush x:Key="CompanyBrush" Color="#7AC040" /> 属性:

Brush

您不能将<Button Content="Click me" Background="{StaticResource CompanyColor}" /> 属性设置为Background的值-只能设置为Color

相关问题