Binding 之ObjectDataProvider数据源

ObjectDataProvider数据源它可以把对象作为数据源提供给Binding,可用于绑定函数,

实例如下

 

 1 public partial class BindObiectDataProvider : Window
 2     {
 3         public BindObiectDataProvider()
 4         {
 5             InitializeComponent();
 6             SetBinding();
 7         }
 8         private void Button_Click(object sender, RoutedEventArgs e)
 9         {
10             ObjectDataProvider odp = new ObjectDataProvider();
11             odp.MethodName = "add";
12             odp.ObjectInstance = new Calculator();
13             odp.MethodParameters.Add("100");
14             odp.MethodParameters.Add("200");
15             MessageBox.Show(odp.Data.ToString());
16 
17         }
18         private void SetBinding()
19         {
20             ObjectDataProvider odp = new ObjectDataProvider();//此类是把对象作为数据源提供给Binding
21             odp.ObjectInstance = new Calculator();
22             odp.MethodName = "add";//指定将要调用Calculator对象总的add方法
23             odp.MethodParameters.Add("0");//相当于告诉odp去调用含有二个参数的add可以用于区分重载,
24             odp.MethodParameters.Add("0");//类型敏感的因add参数为字符串,古此处也应字符串
25             Binding bindingToArg1 = new Binding("MethodParameters[0]")//参数为绑定的路径
26             {
27                 Source = odp,
28                 BindsDirectlyToSource = true,//告诉Binding对象只负责把从UI得到的数据写入Source(odp)而不是写入odp对象包装的Calculator对象中
29                 UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged//枚举值,用于指定更新立即将值回传到Source
30             };
31             Binding bindingToArg2 = new Binding("MethodParameters[1]")
32             {
33                 Source = odp,
34                 BindsDirectlyToSource = true,
35                 UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
36             };
37             Binding bindResulate = new Binding(".") { Source = odp };
38             this.textBoxArg1.SetBinding(TextBox.TextProperty, bindingToArg1);
39             this.textBoxArg2.SetBinding(TextBox.TextProperty, bindingToArg2);
40             this.textBoxResult.SetBinding(TextBox.TextProperty, bindResulate);
41         }
42     }

 

 <StackPanel>
        <Button Content="绑定非暴露的属性(此处为返回值)" Click="Button_Click"></Button>
        <TextBox Margin="10" x:Name="textBoxArg1"></TextBox>
        <TextBox Margin="10" x:Name="textBoxArg2"></TextBox>
        <TextBox Margin="10" x:Name="textBoxResult"></TextBox>
    </StackPanel>
public  class Calculator
    {
      public string add(string str1,string str2)
      {
          double x = 0;
          double y = 0;
          double z = 0;
          if(double.TryParse(str1,out x)&&double.TryParse(str2,out y))
          {
              z = x + y;
              return z.ToString();
          }
          return "Input Error";
      }
    }

 

 

 

转载于:https://www.cnblogs.com/wangboke/p/5320447.html

已标记关键词 清除标记
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页