maxp
maxp

Reputation: 25141

BindingOperations.GetBindingExpression Returning null in WPF

Ive adjusted a bound ViewModel, lets call it MyViewModel to inherit from DependencyObject and switched one of my normal CLR properties, lets call it Name, which used to fire NotifyPropertyChanged() inside the setter, to be a DependencyProperty.

Name is a two-way binding to a TextBox and is working fine.

However, calling BindingOperations.GetBindingExpression(InstantiatedMyViewModel, MyViewModel.NameProperty) always returns null.

1 - Is this because it is not possible to Pass my ViewModel (InstantiatedMyViewModel)in as the first parameter (rather than the instance of the textbox)? I assume that since it's a two-way binding, both the InstantiatedMyViewModeland the TextBox should have some binding knowledge

2 - If it is possible, are there any gotchas im missing?

It's working really well, but when I try to call

Upvotes: 3

Views: 7515

Answers (2)

Grx70
Grx70

Reputation: 10349

I assume you defined the binding in XAML on the TextBox - in that case the text box is the target of the binding, and your view model is the source - there's always a target and a source, and BindingMode.TwoWay only means that the value is updated both ways. Having said that you should know that only the target of the binding has information regarding binding expression.

From BindingOperations.GetBindingExpression on MSDN:

Returns the BindingExpression object associated with the specified binding target property on the specified object.

Upvotes: 3

Chui Tey
Chui Tey

Reputation: 5564

You should use

  var name = InstantiatedMyViewModel.GetValue(MyViewModel.NameProperty)

BindingOperations.GetBindingExpression is used on a control that has a binding to some other object. e.g.

  <TextBox x:Name="textBox1" Text="{Binding Name}" />

Then

  var bindingExpression = BindingOperations.GetBindingExpression(
     textBox1, TextBox.TextProperty);

  // "Name"
  var path = bindingExpression.ParentBinding.Path; 

Upvotes: 5

Related Questions