首页 > 解决方案 > 如何将控件的 BackColor(或其他属性)绑定到存储在 DataSource 中的字符串值?

问题描述

所以我有一个数据库,其中颜色值以 ARBG 格式存储为 INTEGERS。我想要做的是将控件的背景色绑定到数据库,以便颜色根据所选记录与控件背景匹配。(即每条记录都有一种颜色,当表单更改绑定源上的记录显示时,控件背景会更改以匹配数据库中该记录的颜色 INT)。

到目前为止我有这个(这不起作用):

pictureBox1.DataBindings.Add("BackColor", BindingSource1, "ColorINT");

问题是数据库将颜色存储为 INTEGER 并且数据绑定需要颜色,但我无法调用 Color.FromArgb 函数将绑定更改回颜色。我怎样才能做到这一点?

标签: c#.netwinformsdata-bindingproperties

解决方案


感谢 Jimi 的回复,我终于弄明白了。为可能有类似问题的人发帖:

private void IntegerToColor(object sender, ConvertEventArgs cevent)
    {
        if (cevent.DesiredType != typeof(Color)) return;
        cevent.Value = Color.FromArgb(Convert.ToInt32(cevent.Value));
    }

// 然后在表单加载

Binding PicColorBind = new Binding("BackColor", BindingSource1, "ColorINT");
        PicColorBind.Format += new ConvertEventHandler(IntegerToColor);
        picColor.DataBindings.Add(PicColorBind);

推荐阅读