繁体   English   中英

如何为控件的嵌套属性创建数据绑定?

[英]How can I create a databinding for a control's nested property?

考虑以下:

public interface IHaveProperties
{
    public MyProperties Properties { get; set; }
}

public class MyControlA : SomeWinFormsControl, IHaveProperties { ... }

public class MyControlB : SomeOtherWinFormsControl, IHaveProperties { ... }

public class MyProperties
{
    public int Foo { get; set; }
    public string Bar { get; set; }
    public double Baz { get; set; }
    ...
}

这使我们可以将相同的附加属性添加到许多其他我们无法修改其基类的控件,以及保存/加载属性集。

现在,我们有了大约十二种不同的MyControlX,我们已经意识到能够将数据绑定到Properties.Bar很好。

显然,我们可以这样做:

public interface IHaveProperties
{
    public MyProperties Properties { get; set; }
    public string Bar { get; set; }
}

public class MyControlA : SomeWinFormsControl, IHaveProperties
{
    public string Bar
    {
        get { return Properties.Bar; }
        set { Properties.Bar = value; }
    }
}

...但是我们必须将相同的代码放入十几个控件中的每个控件中,这看起来有点臭。

我们尝试了这个:

// Example: bind control's property to nested datasource property
myTextBox.DataBindings.Add(new Binding("Text", myDataSet, "myDataTable.someColumn"))
// works!

// bind control's (nested) Properties.Bar to datasource
myTextBox.DataBindings.Add(new Binding("Properties.Bar", someObject, "AProperty"))
// throws ArgumentException!

是否可以通过某种方式构造绑定或修改MyProperties类,而不是对所有控件进行相同的更改来绑定到myControl.Properties.Bar

不应该是这样的:

TextBox.DataBindings.Add(new Binding("Text", someObject, "Properties.Bar"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM