您的位置:首页 > 移动开发 > Objective-C

数据绑定(七)使用ObjectDataProvider对象作为Binding的Source

2011-12-07 20:26 676 查看
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";
}


界面代码很简单,有三个输入框

<TextBox x:Name="textBoxArg1" Margin="5" />
<TextBox x:Name="textBoxArg2" Margin="5" />
<TextBox x:Name="textBoxResult" Margin="5" />


后台代码:

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对象,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐