:如何超越编写用于数据绑定多个控件(没有内置数据源属性的控件)的技术的自定义实现,
对于每种可能的数据类型
,到简单属性。。。
... 实现一个更强大的解决方案,该解决方案将独立于绑定到字符串、int或其他类型。
我的猜测是:这将涉及反思;但是,我被困在那一点上。我在寻找关于下一步行动方向的战略建议,提示,线索,不是一个完整的代码答案,但我当然感谢所有的回答,如果你在回复中发布代码,我一定会研究代码!Marc Clifton 2005年关于CodeProject的文章
Simple Databinding
:似乎演示了一种基于反射的方法:但是,老实说,我并没有真正研究他的代码,而且,就.NET而言,2005是一个
长的
很久以前。
背景:部分是为了回答各种问题和答案,如:
Update Usercontrol on Three Forms
:我开发了一种成功的技术,可以将各种控件的文本属性同时数据绑定到公共类中定义的一个源;我们还可以使用定义一个扩展方法和两个公共方法的静态类来“抽象”绑定过程的一些细节。
我已经验证了“MainForm”中控件上的TextBox、MainForm中UserControl上的TextBox以及“独立”打开的第二个窗体上的TextBox(即form2.Parent==null)都从“DataSource equivalent”公共类正确更新(即双向绑定生效)。改变一:改变一切。
代码:此类的实例将为数据绑定提供目标属性(文本):
public class TextDataBinder
{
public event PropertyChangedEventHandler PropertyChanged;
private string _theText;
public string theText
{
get { return _theText; }
// note : if 'setter is declared 'internal : blocks
// auto-updating when run-time user modifies consumers
// but will still allow update via code
set
{
_theText = value;
OnPropertyChanged(new PropertyChangedEventArgs("theText"));
}
}
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, e);
}
}
}
代码:此静态类允许隐藏一些绑定过程的复杂性,并允许轻松绑定到多个控件:
public static class TextBindingExtender
{
public static TextDataBinder CurrentDataSource;
public static void SetCurrentDataSource(TextDataBinder newCurrentDataSource)
{
CurrentDataSource = newCurrentDataSource;
}
// extension method for Control
public static void AddTextBinding(this Control theControl, string controlPropertyName, string targetPropertyName)
{
theControl.DataBindings.Add(controlPropertyName, CurrentDataSource, targetPropertyName, false, DataSourceUpdateMode.OnPropertyChanged);
}
// bind to all Controls in a List<Control>
public static void AddTextBindings(List<Control> theControls, string controlPropertyName, string targetPropertyName)
{
foreach (Control theControl in theControls)
{
theControl.AddTextBinding(controlPropertyName, targetPropertyName);
}
}
}
如何使用上述类(在窗体加载事件中):
// create a new TextDataBinder
TextBindingExtender.CurrentDataSource = new TextDataBinder();
// bind to multiple textboxes, label, on a UserControl, on another Form, etc.
TextBindingExtender.AddTextBindings(new List<Control> { textBox1, textBox2, userControl11.tb, label1, instanceOfForm2.tb }, "Text", "theText");
// test assigning some initial text to the bound property
TextBindingExtender.CurrentDataSource.theText = "some initial text";