C# 中的数据绑定自定义 XML 可序列化 Color 类
我有一个 SerializedColor 类,允许我对颜色进行 XML 序列化。
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; }
}
现在,例如,考虑一个 Foo 类:
public class Foo
{
public SerializableColor SColor { get; set; }
}
我想将一些 WinForm Control 属性数据绑定到该类。 当我第一次添加数据绑定时,一切正常,但任何更改都无法正确传播。
例如,如果我将控件的 BackColor 绑定到 SColor,则 BackColor 将正确更新等。但是,如果我随后去更改 BackColor,则更改将不会传播到 Foo 对象的 SColor。如果我更改 Foo 对象的 SColor,则在 Control 的 BackColor 上将看不到更改。
到纯 Color 属性的数据绑定可以按需要工作。只是不是 SerializedColor。
我哪里错了?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使 SerializedColor 类实现 INotifyPropertyChanged。
如果 SColor 完全更改为新的颜色实例,您还应该让 Foo 实现它。
另外,如果您希望 Windows 窗体能够与 SerializedColor 类型进行双向转换。
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.