user1909412
user1909412

Reputation: 87

Change color StackPanel, according to the data received from the Binding, in XAML

I want to change the color of a StackPanel, according to the data (1, 2, 3...) received from the Binding (value), which should I use?

<StackPanel Grid.Column="1">
   <Border Height="50" Width="Auto" Margin="3" Background="Black">
      <TextBlock FontSize="18" FontWeight="Bold" TextWrapping="Wrap" Foreground="White" 
                 Text="{Binding valor}" VerticalAlignment="Center"
                 HorizontalAlignment="Center"/>
   </Border>
</StackPanel>

Upvotes: 1

Views: 2761

Answers (2)

user1909412
user1909412

Reputation: 87

I fixed it by making a new variable in the class, and calling this new, in the xaml (Background="{Binding customBackground}")

public object customBackground
    {
    get
    {
    if (color == "1")//GREEN 
        {
            return new SolidColorBrush(Color.FromArgb(255, 7, 166, 45));
        }
    if (color == "2")//RED
        {
            return new SolidColorBrush(Color.FromArgb(255, 230, 5, 10));
        }
    if (color == "3")//BLUE
    {
        return new SolidColorBrush(Color.FromArgb(255, 6, 102, 210));
    }
    if (color == "4")//YELLOW
    {
        return new SolidColorBrush(Color.FromArgb(255, 189, 211, 3));
    }
    // Color por defecto
    return new SolidColorBrush(Colors.Gray);
    }
    }

Upvotes: 0

robertk
robertk

Reputation: 2461

Use a converter: http://www.smallandmighty.net/blog/using-value-converters-to-change-the-visibility-of-a-control

<Window.Resources>
    <converters:ColorConverter x:Key="ColorConverter"/>
</Window.Resources>

XAML:

  <StackPanel Background="{Binding valor, Converter={StaticResource ColorConverter}}"/>

Your converter would look something like this:

public class ColorConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,CultureInfo culture)
    {
        if (value != null)
        {
            int Value = (int)value;

            if(Value == 1)
               return Colors.Green;
             else if(Value == 2)
               return Colors.Red;
[...]
            }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

Upvotes: 4

Related Questions