2014-06-16 85 views
4

考虑以下几点:如何为控件的嵌套属性创建数据绑定?

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某种方式?

+0

AA的最低,我认为你需要实现双方INotifyPropertyChanged的。 – Maarten

+0

相关:http://stackoverflow.com/questions/8894103/does-data-binding-support-nested-properties-in-windows-forms – Maarten

+1

@Maarten是的。该问题涵盖了绑定的数据源端的属性嵌套,而我的内容则是关于控件端的属性嵌套。 –

回答

-2

它不应该是这样的:

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

你应该解释一下为什么你的解决方案有效。 –

+0

不是。问题是我想将myTextBox.Properties.Bar绑定到someObject.AProperty。 –

相关问题