WPF数据绑定依赖DependencyProperty和INotifyPropertyChanged,ViewModel需实现该接口并触发PropertyChanged事件,View通过DataContext关联ViewModel,Binding路径须为public属性且区分大小写,集合应使用ObservableCollection。
WPF 中的数据绑定核心是 依赖属性(DependencyProperty) 和 INotifyPropertyChanged 接口,MVVM 模式下,View 绑定 ViewModel 的属性,靠的是这两者配合实现自动更新。
这是让 UI 感知数据变化的关键。不实现它,修改属性值后界面不会刷新。
INotifyPropertyChanged 接口OnPropertyChanged 方法,内部调用 PropertyChanged?.Invoke(...)
[CallerMemberName] 避免硬编码字符串)示例:
public class MainViewModel : INotifyPropertyChanged
{
private string _title = "默认标题";
public string Title
{
get => _title;
set
{
if (_title != value)
{
_title = value;
OnPropertyChanged(); // 自动获取属性名
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
绑定生效的前提是 View 知道该找谁要数据。通常在窗口或控件初始化时设置 DataContext。
this.DataContext = new MainViewModel();
DataContext 属性直接实例化(适合简单场景):
绑定语法灵活,常见写法有:
Text="{Binding Title}" —— 默认 Mode=OneWay,绑定到 ViewModel 的 Title 属性Text="{Binding Path=Title, Mode=TwoWay}" —— 显式指定双向绑定(如 TextBox 输入后同步回 ViewModel)ItemsSource="{Binding Products}" —— 绑定集合,配合 ListBox 或 DataGrid 使用Command="{Binding SaveCommand}" —— 绑定 ICommand 实现(如 RelayCommand),响应按钮点击等操作注意:Binding 路径区分大小写,且只支持 public 属性,不支持字段。
如果绑定的是列表(比如显示商品列表),ViewModel 中的集合必须是 ObservableCollection 或其它能触发通知的集合类型。
List 不会通知新增/删除,改了也不会刷新 UIObservableCollection 在 Add/Remove/Clear 时自动触发 CollectionChanged 事件CollectionViewSource 包装,支持分组、筛选、当前项跟踪基本上就这些。WPF 数据绑定不复杂但容易忽略细节,关键是 ViewModel 可通知、View 有上下文、Binding 写对路径——三者齐备,自动联动就跑起来了。