Datacontext 属性是 View 的所有绑定的默认来源。
在 MVVM 中,Datacontext 用于将 ViewModel 链接到 View。
由于Datacontext属性是一个依赖属性,如果不在控件中定义它,它会继承自他的父亲等等。
这是 MVVM 实现的示例:
所有 ViewModel 类的父级(在所有 ViewModel 中实现 INotifyPropertyChanged):
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
注意:INotifyPropertyChanged 允许您的 ViewModel 通知 View 更改(用于绑定)。
假设我希望将 MainWindows(视图)链接到 ViewModel:
public MainWindow()
{
InitializeComponent();
MainViewModel mainViewModel = new MainViewModel(this);
this.DataContext = mainViewModel;
}
对于 ViewModel :
class MainViewModel : ViewModelBase
{
#region fields
private MainWindow mainWindow;
private string message = "Hello world !";
#endregion
#region properties
public MainWindow MainWindow
{
get
{
return this.mainWindow;
}
}
public string Message
{
get
{
return message;
}
set
{
this.message = value; OnPropertyChanged("Message");
}
}
// ...
#endregion
public MainViewModel(MainWindow mainWindow)
{
this.mainWindow = mainWindow;
}
}
所以现在如果我想在我的视图(主窗口)中绑定 MainViewModel 的一个属性,我只需要在我的 ViewModel 中有一个公共属性并在我的 XAML 中创建一个绑定。我不必指定源,因为 DataContext 是默认源。
所以我可以添加 MainWindow.xaml :
<TextBox Text="{Binding Message}" />