本文共 1971 字,大约阅读时间需要 6 分钟。
ObjectDataProvider就是把对象作为数据源提供给Binding,类似的还有XmlDataProvider,也就是把XML数据作为数据源提供给Binding,这两个类的父类都是DataSourceProvider抽象类
举例
有一个Calculator类,提供了一个Add方法
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 "Error"; }界面代码很简单,有三个输入框
后台代码:
ObjectDataProvider odp = new ObjectDataProvider(); odp.ObjectInstance = new Calculator(); odp.MethodName = "Add"; odp.MethodParameters.Add("0"); odp.MethodParameters.Add("0"); Binding bindingToArg1 = new Binding(); bindingToArg1.Source = odp; bindingToArg1.Path = new PropertyPath("MethodParameters[0]"); bindingToArg1.BindsDirectlyToSource = true; bindingToArg1.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; Binding bindingToArg2 = new Binding(); bindingToArg2.Source = odp; bindingToArg2.Path = new PropertyPath("MethodParameters[1]"); bindingToArg2.BindsDirectlyToSource = true; bindingToArg2.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; Binding bindingToResult = new Binding(); bindingToResult.Source = odp; bindingToResult.Path = new PropertyPath("."); textBoxArg1.SetBinding(TextBox.TextProperty, bindingToArg1); textBoxArg2.SetBinding(TextBox.TextProperty, bindingToArg2); textBoxResult.SetBinding(TextBox.TextProperty, bindingToResult);首先定义了一个 ObjectDataProvider对象并与Calculator类的Add方法进行关联,把第一个输入框中的内容同函数的参数1进行绑定,第二个输入框中的内容同函数的参数2进行绑定,函数的返回值与第三个输入框绑定,BindsDirectlyToSource = true这句代码的意思是,Binding对象只负责把从UI元素收集到的数据写入其直接Source(即ObjectDataProvider对象)而不是被ObjectDataProvider对象包装着的Calculator对象,
转载地址:http://ghdul.baihongyu.com/