Search code examples
c#wpfxamlcolorsbrush

How to set a background colour in xaml.cs file?


I have a XAML, containing following entry:

<TextBlock Text="{Binding Info40}"
           HorizontalAlignment="Center"
           Background="{Binding Info40_OK}">

I have the following code in the XAML.cs file, which fills in the binded value:

Info40   = source.Info40;

=> This is working fine.

Now I also want to alter the background colour, which I tried as follows:

if (Info40 >= 20) Info40_OK = Colors.DarkGreen else { Info40_OK = Colors.Red; }

This does not work, as Info40_OK is a Brush, while Colors.DarkGreen is a Color, while in the XAML, using a fix colour is working fine as follows:

Background="DarkGreen"

So, simple question: how can I set the Info40_OK value as DarkGreen in the XAML.cs file?


Solution

  • In XAML, the Background property expects a Brush object, not just a Color. When you set Background="DarkGreen" in XAML, it automatically creates a SolidColorBrush with the DarkGreen color for you.

    To set the Info40_OK property to a Brush with the DarkGreen color in your code-behind (XAML.cs), you need to create a SolidColorBrush with the DarkGreen color and assign it to the Info40_OK property. Here's how you can do it:

        using System.Windows.Media;
    
    // ...
    
    // Calculate Info40_OK based on the condition
    if (Info40 >= 20)
    {
        Info40_OK = new SolidColorBrush(Colors.DarkGreen);
    }
    else
    {
        Info40_OK = new SolidColorBrush(Colors.Red);
    }
    

    This code creates a SolidColorBrush with the DarkGreen or Red color based on your condition, and then assigns it to the Info40_OK property, which is what XAML expects for the Background property of the TextBlock.