我使用Window.xaml.cs構造函數(DataContext = WindowVM
)中的DataContext
將我的wpf窗口綁定到應用程序層類(WindowVM.cs)。但是,一個控件(btnAdd
)我想要綁定到Window.xaml.cs屬性。因此,在Window.xaml.cs構造函數中,我添加了this.btnAdd.DataContext
。這是Window.xaml.cs構造和財產,我想結合Button
btnAdd
:將一個控件綁定到另一個的DataContext
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'...
在接下來的調用中沒有任何控制檯輸出錯誤的屬性添加。
現在我有點困惑,因爲這個錯誤。這是因爲第一個DataContext
(對WindowVM)的錯誤,因爲沒有屬性添加,但行this.btnAdd.DataContext
屬性添加被發現,這是它的工作原因?
那麼,爲什麼你使用MVVM(或類似的),如果你不打算在ViewModel命令? ViewModel應該是Command的位置。後面的窗口代碼應該真的有零碼。 –
我把命令放在ViewModel中,但有問題,因爲我需要關閉窗口。此綁定工作:{Binding ElementName = MyUsersView,Path = Add}。但是,我會嘗試這個:http://blog.excastle.com/2010/07/25/mvvm-and-dialogresult-with-no-code-behind/然後把命令放在ViewModel中。 – davor