我使用DataContext
将我的WPF窗口绑定到应用程序层类(WindowVM.cs),并将其放置在Window.xaml.cs构造函数中(DataContext = WindowVM
)。但是,我想将一个控件(btnAdd
)绑定到Window.xaml.cs属性。因此,在Window.xaml.cs构造函数中,我添加了this.btnAdd.DataContext
。这是Window.xaml.cs构造函数和我想要绑定Button
btnAdd
的属性:
public Window()
{
InitializeComponent();
DataContext = WindowVM;
this.btnAdd.DataContext = this;
}
public RelayCommand Add
{
get
{
return _add == null ? _add= new RelayCommand(AddPP, CanAddPP) : _add;
}
set
{
OnPropertyChanged("Add");
}
}
Xaml长成这个样子(类PP是WindowVM属性):
<TextBox Name="txtName" Text="{Binding PP.Name, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Name="txtSurname" Text="{Binding PP.Surname, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding Add}" Content="Add" ... />
一切正常,但控制台输出如下:
BindingExpression path error: 'Add' property not found on 'object' ''WindowVM'...
下一次调用 Add 属性时不会出现任何控制台输出错误。
现在我有点困惑这个错误是因为第一个 DataContext
(给 WindowVM)导致的,因为没有 Add 属性,但是通过 this.btnAdd.DataContext
这一行代码,Add 属性被找到并且这就是它正常工作的原因吗?