BindingOperations.GetBindingExpression 在 WPF 中返回 null

max*_*axp 3 c# wpf binding

我已经调整了一个绑定的 ViewModel,让我们调用它MyViewModel来继承DependencyObject并切换我的一个普通 CLR 属性,让我们调用它Name,它曾经NotifyPropertyChanged()在 setter 中触发,成为DependencyProperty.

Name是对 a 的双向绑定,TextBox并且工作正常。

但是,调用BindingOperations.GetBindingExpression(InstantiatedMyViewModel, MyViewModel.NameProperty)始终返回 null。

1 - 这是因为不可能将我的 ViewModel ( InstantiatedMyViewModel) 作为第一个参数(而不是文本框的实例)传入?我认为既然是双向绑定, theInstantiatedMyViewModel和 theTextBox都应该有一些绑定知识

2 - 如果可能的话,我是否遗漏了什么陷阱?

它工作得很好,但是当我尝试打电话时

Chu*_*Tey 5

你应该使用

  var name = InstantiatedMyViewModel.GetValue(MyViewModel.NameProperty)
Run Code Online (Sandbox Code Playgroud)

BindingOperations.GetBindingExpression用于绑定到其他对象的控件。例如

  <TextBox x:Name="textBox1" Text="{Binding Name}" />
Run Code Online (Sandbox Code Playgroud)

然后

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

  // "Name"
  var path = bindingExpression.ParentBinding.Path; 
Run Code Online (Sandbox Code Playgroud)