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

12k views Asked by At

Just a short question :
In wpf, how do I set and get updatesourcetrigger of a textbox in codebehind ?
Thanks

Update :
I follow AngleWPF's code :

        var bndExp = BindingOperations.GetBindingExpression(this, TextBox.TextProperty);

        var myBinding
          = bndExp.ParentBinding;

        var updateSourceTrigger = myBinding.UpdateSourceTrigger;

But I got the exception :

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll Additional information: Exception has been thrown by the target of an invocation.

3

There are 3 answers

6
Vinit Sankhe On BEST ANSWER

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.

0
S.Mishra On

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.

0
Ankush Madankar On

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);