public MainWindow() { InitializeComponent(); stu = new Student(); stu.SetBinding(Student.NameProperty, new Binding("Text") { Source = TextBox1 }); TextBox2.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu }); }
private void SetBinding() { ConvertModels convert = new ConvertModels(); ObjectDataProvider odp = new ObjectDataProvider(); ValidRule rule = new ValidRule(); odp.ObjectInstance = cal; odp.MethodName = "Add"; odp.MethodParameters.Add(0); //由参数自动选择使用的是哪个重载函数 odp.MethodParameters.Add(0); Binding bind = new Binding("MethodParameters[0]") { Source = odp, BindsDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Converter = convert }; bind.ValidationRules.Add(rule); bind.NotifyOnValidationError = true; Binding bind1 = new Binding("MethodParameters[1]") { Source = odp, BindsDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Converter = convert }; //bind1.ValidationRules.Add(rule); bind1.NotifyOnValidationError = true; Binding bind2 = new Binding(".") { Source = odp }; TextBox1.SetBinding(TextBox.TextProperty, bind); //BindsDirectlyToSource指示绑定的方向 TextBox2.SetBinding(TextBox.TextProperty, bind1); TextBox3.SetBinding(TextBox.TextProperty, bind2); //1、ObjcetDataProvider的MethodParameter不是依赖属性,不能作为Binding的目标。 //2、数据驱动UI理念要求我们尽可能的使用数据对象作为Binding的Source而把UI当做Binding的Target。 //捕捉校验事件 Grid1.AddHandler(Validation.ErrorEvent, new RoutedEventHandler((o, args) => { //Validation.GetErrors(o as FrameworkElement); if (Validation.GetErrors(TextBox1).Count > 0) { Console.WriteLine("Sender: " + (args.OriginalSource as FrameworkElement).Name + " Error: " + Validation.GetErrors(TextBox1)[0].ErrorContent); } if (Validation.GetErrors(TextBox2).Count > 0) { Console.WriteLine("Sender: " + (args.OriginalSource as FrameworkElement).Name + " Error: " + Validation.GetErrors(TextBox2)[0].ErrorContent); } })); }