简体   繁体   中英

How can I define a Static Resource in C# instead of XAML?

I have this code:

<ResourceDictionary>
   <Color x:Key="WordTextColor">#2196f3</Color>
</ResourceDictionary>

<Grid>
   <Grid.Resources>
      <Style TargetType="Grid">
         <Style TargetType="Label">
            <Setter Property="TextColor" Value="{StaticResource WordTextColor}" />
      </Style>

How can I code this in C#

Also can I code up this Static Resource as a string instead of a Color?

You can have a helper class, like this, where you define all your colors / values

public static class Styles
{
    private static Color _backgroundColor = Color.FromHex("151515");
    public static Color BackgroundColor => _backgroundColor;
}

Then, in xaml, you reference it in the header:

xmlns:local="clr-namespace:YourProjectAssembly.YourName;assembly=YourProjectAssembly.YourName"

And to use it:

<Grid BackgroundColor="{x:Static local:Styles.BackgroundColor}"/>

Color can be set in String values instead of Hexa values.
Resources can be set in Window.Resources or Grid.Resources.

Resources in Window level

<Window.Resources>
   <Color x:Key="TheBackgroundColor">#2196f3</Color>
</Window.Resources>

<Grid>
  <Style TargetType="Grid">
     <Style TargetType="Label">
        <Setter Property="TextColor" Value="{StaticResource TheBackgroundColor}" />
  </Style>
</Grid>

Resources in Grid level

<Grid>
  <Grid.Resources>
     <Color x:Key="TheBackgroundColor">#2196f3</Color>
  </Grid.Resources>
  <Style TargetType="Grid">
     <Style TargetType="Label">
        <Setter Property="TextColor" Value="{StaticResource TheBackgroundColor}" />
  </Style>
</Grid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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