0

I have this field in my object, I want to bind to a rectangle

public string FillVal { get; set; }

I set this field with one of these values:

    public const string GREENRIBBON = "#FF7CB84D";
    public const string ORANGERIBBON = "#FFECB74D";
    public const string REDRIBBON = "#FFFF4741";

The rectangle I use it set up like this:

<Rectangle x:Name="Level"
    Fill="{Binding FillVal}"
    HorizontalAlignment="Left"
    Height="115"
    VerticalAlignment="Top"
    Width="6"
    Margin="-2,0,0,0" />

But when I launch the app, I won't apply this property to the rectangle.

Why?

Saphire
  • 1,812
  • 1
  • 18
  • 34

3 Answers3

1

The Rectangle.Fill takes a Brush object, so you have to create a Brush from your color string. You can use this helper method:

private SolidColorBrush GetBrushFromHexString(string hexString)
    {
        hexString = hexString.Replace("#", "");
        int colorInt = Int32.Parse(hexString, NumberStyles.HexNumber);

        byte a = (byte)(colorInt >> 24);
        byte r = (byte)(colorInt >> 16);
        byte g = (byte)(colorInt >> 8);
        byte b = (byte)colorInt;

        Color color = Color.FromArgb(a, r, g, b);

        return new SolidColorBrush(color);
    }



FillVal = GetBrushFromHexString("#FF7CB84D");
Gerrit Fölster
  • 984
  • 9
  • 18
0

Rectangle.Fill is of type System.Windows.Media.Brush and you are trying to pass a String value to it. This works in XAML because the Brush type has an automatic converter from string. This however will not work when binding it.

http://msdn.microsoft.com/en-us/library/system.windows.media.brush(v=vs.110).aspx

You can use this converter yourself by looking at How to get Color from Hexadecimal color code using .NET?

Then you can use the SolidColorBrush constructor:

var brush = new SolidColorBrush(myColor);

Community
  • 1
  • 1
Bas
  • 26,772
  • 8
  • 53
  • 86
0

Saphire, your example run perfectly. Just missing you binding window DataContext with window codebehind, with this code in the window constructor:

this.DataContext = this;

My recomendation is use the App.xaml or ResourceDictionarys for this practices:

<Application x:Class="WpfApplication2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <SolidColorBrush x:Key="GREENRIBBON" Color="#FF7CB84D" />
        <SolidColorBrush x:Key="ORANGERIBBON" Color="#FFECB74D" />
        <SolidColorBrush x:Key="REDRIBBON" Color="#FFFF4741" />
    </Application.Resources>
</Application>

And for dynamic use, find your value in code:

Brush GreenRibbon  = (Brush)Application.Current.FindResource("GREENRIBBON");
Brush OrangeRibbon = (Brush)Application.Current.FindResource("ORANGERIBBON");
Brush RedRibbon    = (Brush)Application.Current.FindResource("REDRIBBON");

Regards !!!

PakKkO
  • 154
  • 5