【问题标题】:How can I create a databinding for a control's nested property?如何为控件的嵌套属性创建数据绑定?
【发布时间】:2014-08-06 19:12:32
【问题描述】:

考虑以下几点:

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; }
    ...
}

这允许我们将相同的附加属性添加到我们无法修改其base class 的许多不同控件,以及保存/加载属性集。

现在我们有大约十几个不同的 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,而不是对所有控件进行相同的更改?

【问题讨论】:

  • Aa 至少我认为你需要在两边都实现 INotifyPropertyChanged。
  • @Maarten 是的。这个问题涉及绑定的数据源端的属性嵌套,而我的问题是关于控件端的属性嵌套。

标签: c# winforms data-binding


【解决方案1】:

不应该是这样吗:

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

【讨论】:

  • 没有。问题是我想将 myTextBox.Properties.Bar 绑定到 someObject.AProperty。
猜你喜欢
  • 2023-03-13
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
相关资源
最近更新 更多