深入浅出WPF 第二部分(8)
6.3.11 使用ObjectDataProvider对象作为Binding的Source
ObjectDataProvider,顾名思义就是把对象作为数据源提供给Binding。前面还提到过XmlDataProvider,也就是把XML数据作为数据源提供给Binding。这个类的父类都是DataSourceProvider。
public MainWindow() { InitializeComponent(); SetBinding(); } private void SetBinding() { ObjectDataProvider odp = new ObjectDataProvider(); odp.ObjectInstance = new Calculator(); odp.MethodName = "Add"; odp.MethodParameters.Add("0"); odp.MethodParameters.Add("0"); this.textBox1.SetBinding(TextBox.TextProperty, new Binding() { Source = odp, Path = new PropertyPath("MethodParameters[0]"), BindsDirectlyToSource = true, UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged }); this.textBox2.SetBinding(TextBox.TextProperty, new Binding() { Source = odp, Path = new PropertyPath("MethodParameters[1]"), BindsDirectlyToSource = true, UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged }); this.textBlock1.SetBinding(TextBlock.TextProperty, new Binding() { Source = odp, Path = new PropertyPath("."), }); } } public class Calculator { public string Add(string arg1, string arg2) { double x = 0; double y = 0; double z = 0; if (double.TryParse(arg1, out x) && double.TryParse(arg2, out y)) { z = x + y; return z.ToString(); } return "Input error!"; } }