Question

I have setup binding as follows

XAML

 <TextBlock Text="{Binding Path=Color, Converter={StaticResource ColorToStringConverter}}" />

C#: Showing what Color is

public System.Windows.Media.Color Color
{
    get
    {
        var color = new HSLColor { Hue = this.Hue, Saturation = this.Saturation, Luminosity = this.Luminosity };
        string strColor = color.ToRGBString();
        return new System.Windows.Media.Color { 
            R = byte.Parse(strColor.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
            G = byte.Parse(strColor.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
            B = byte.Parse(strColor.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)
        };
    }
    set { SetValue(ColorProperty, value); }
}

Converter

public class ColorToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Color color = (Color)value;
        return color.ToString();
    }
}

But my converter is getting value like

value = "{Name=0, ARGB=(0, 0, 0, 0)}"

I'd expect it to be a System.Windows.Media.Color why am I getting this?

Basically, I have 3 Silders for HSL values bound to DependencyProperties, each have a PropertyChangedCallback attached to them

new PropertyChangedCallback(HSLValuePropertyChanged)

It looks like

protected void HSLValueChanged()
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs("Color"));
}

Basically its purpose is to update controls bound to the dependency property Color. The idea is that get should run for property Color which creates a new color from HSL properties. The problem it seems is that the get does not run even when I change HSL values.

UPDATE

So I tried to return just value in the case of an exception, I got nothing in the textbox, so i did value.toString() got Color [Empty] all the time. What did I do wrong?

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    try
    {
        Color color = (Color)value;
        return color.ToString();
    } catch (Exception) {
        return value.ToString();
    }
}
Was it helpful?

Solution

You seem to be using the ColorDependencyProperty. If so, I think the binding may never actually go trough the accessors (get/set) ...

You should set the new color (in the dependencyProperty via the setvalue method) on each of your H/S/L properties change call back...

I hope i am clear :-)

OTHER TIPS

When bound on a DependencyProperty, bindings dont use property getters to obtain values, so, all the code you put in the Color property getter is skipped as far as bindings are concerned.

Stick to defining your getters as get { return (XXX)GetValue(MyProperty); } and find another way around.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top