views:

277

answers:

1

I have a class, SerializableColor, to allow me to XML serialize Colors.

public class SerializableColor
{

    // omitted constructors, etc. ...

    [XmlIgnore]
    public Color Color
    {
        get { return Color.FromArgb(this.Alpha, this.Red, this.Green, this.Blue); }
        set
        {
            this.Alpha = value.A;
            this.Red = value.R;
            this.Green = value.G;
            this.Blue = value.B;
        }
    }

    public int Alpha { get; set; }
    public int Red { get; set; }
    public int Green { get; set; }
    public int Blue { get; set; }
}

Now, for example, consider a class Foo:

public class Foo 
{
    public SerializableColor SColor { get; set; }
}

I want to databind some WinForm Control properties to this class. When I first add the databinding, everything works fine, but any changes are not correctly propogated.

For example, if I bind a Control's BackColor to SColor, the BackColor will be correctly updated, etc. However, if I then go and change the BackColor, the change will not be propogated to the Foo object's SColor. And if I change the Foo object's SColor, the change will not be seen on the Control's BackColor.

Databinding to a plain Color property works as desired. Just not to a SerializableColor.

Where am I going wrong?

+3  A: 

You need to make your SerializableColor class implement INotifyPropertyChanged.

You should also make Foo implement it if SColor is changed to a new color instance entirely.

Also, you should really implement a TypeConverter if you want Windows Forms to be able to bi-directionally convert to/from your SerializedColor type.

Josh Einstein