3

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

2
  • 1
    "I assume that since it's a two-way binding, both the InstantiatedMyViewModeland the TextBox should have some binding knowledge". That assumption is wrong. You can't get a binding expression from the source of a binding, only from the target, even if it's two-way. Commented Oct 12, 2015 at 12:12
  • Just an FYI, it is generally preferred that your ViewModels implement the INPC interface instead of inheriting from DependencyObject. Commented Oct 12, 2015 at 12:19

2 Answers 2

5

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; 
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.