How to set and get updatesourcetrigger of a textbox in codebehind?

我的梦境 提交于 2019-12-01 11:46:14

What do you mean by UpdateSourceTrigger of TextBox? You mean to say UpdateSourceTrigger of TextBox.TextProperty's Binding?

E.g. if you have a TextBox named myTextBox having its Text property bound to some source then you can easily get it's UpdateSourceTrigger and Binding object via GetBindingExpression() call.

   var bndExp
     = BindingOperations.GetBindingExpression(myTextBox, TextBox.Textproperty);

   var myBinding
     = bndExp.ParentBinding; 

   var updateSourceTrigger
     = myBinding.UpdateSourceTrigger;

But it is tricky to set UpdateSourceTrigger for an already used binding. E.g. in the above case you wont be able to set the myBinding.UpdateSourceTrigger to something else. This is not allowed when a binding object is already in use.

You may have to deep clone the binding object and set new UpdateSourceTrigger to it and assign it back to the TextBox. Cloning does not exist for Binding class. You may have to write your own cloning code for the same.

  var newBinding = Clone(myBinding); //// <--- You may have to code this function.
  newBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
  myTextBox.SetBinding(TextBox.TextProperty, newBinding);

Alternately ou can also try to detatch the existing Binding and update it and assign it back...

  myTextBox.SetBinding(TextBox.TextProperty, null);
  myBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
  myTextBox.SetBinding(TextBox.TextProperty, myBinding);

Let me know if any of these tips helps.

A another way to implement it is setting binding in TextBox loaded eventhandler. Below is the xaml of TextBox:

    <TextBox Grid.Row="0" 
             x:Name="txtName"
             Text="{Binding Name}"
             Loaded="TxtName_OnLoaded" />

Now in code behind for TxtName_OnLoaded eventhandler will will create new Binding object and will initialize it as per our needs. Also we will add ValidationRule into it.

    private void TxtName_OnLoaded(object sender, RoutedEventArgs e)
    {
      ApplicationViewModel appVm = this.DataContext as ApplicationViewModel;
      TextBox TxtName = sender as TextBox;

      if (TxtName == null)
        return;

      Binding newBinding = new Binding("Name");
      newBinding.ValidatesOnDataErrors = true;
      newBinding.ValidatesOnExceptions = true;
      newBinding.NotifyOnValidationError = true;
      newBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
      validator.ErrorMessage = "Labware name should be unique.";
      validator.ApplicationViewModel = appVm;
      if (!newBinding.ValidationRules.Contains(validator))
        newBinding.ValidationRules.Add(validator);
      TxtName.SetBinding(TextBox.TextProperty, newBinding);
    }

As you can see in above implementation we have created an object of Binding with new binding path. Also assigned UpdateSourceTrigger to newly created Binding object.

A binding can have multiple validation rules. We will add a validation rule into it. Now we can set the binding to the TextProperty of textbox.

Benefits: You can bind multiple dependency objects to the properties of Validation Rule object from code behind which is not possible with xaml. For example:

I used it to validate inputs on TextChanged event, where I compare input with the list of Items stored as public ObservableCollection property, bound with Grid, in ApplicationViewModel. Code of ValidationRule is as follows:

    public class UniqueValueValidator : ValidationRule
  {
    public string ErrorMessage { get; set; }
    public ApplicationViewModel ApplicationViewModel { get; set; }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
      if (value == null)
        return null;

      var lws = ApplicationViewModel.Inputs.Where(s => s.Name.Equals(value.ToString())).FirstOrDefault();
      if (lws != null)
        return new ValidationResult(false, ErrorMessage);


      return new ValidationResult(true, null);
    }
  }

Above code takes input and checks availability in the "Inputs" observable collection. Rule give false ValidationResult if value exists. Through this implementation I check uniqueness of inputs on run-time.

Hope you guys have enjoyed it.

I think this the right way to do this:

 Binding binding = new Binding();

 binding.Source = new CustomerViewModel();;
 binding.Path = new PropertyPath("Customer.Name");
 binding.Mode = BindingMode.TwoWay;
 binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
 txtCustName.SetBinding(TextBox.TextProperty, binding);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!