WPF中绑定的数据源
一、什么是「绑定数据源」?
一句话定义:
数据源 = 绑定的源头,也就是 {Binding} 取值的那个对象。
你写:
1 <TextBlock Text="{Binding Name}" />
WPF 一定会问:
Name 是哪个对象里的?这个对象就是数据源!
二、WPF 数据源的 5 大类型(全覆盖)
WPF 所有绑定,数据源只有这 5 种,记住就永远不会乱:
1. DataContext(默认数据源,最常用)
2. ElementName(界面控件 → 界面控件)
3. RelativeSource(自己 / 父元素 / 模板内绑定)
4. Source(直接指定资源 / 静态对象)
5. 后台 .NET 对象 / 集合(MVVM 核心)
下面我一个一个详细讲 + 举例。
三、数据源 1:DataContext(默认数据源,90% 场景)
作用
整个界面 / 控件的默认数据源,所有子元素自动继承。
不用写 Source,直接 {Binding 属性}。
不用写 Source,直接 {Binding 属性}。
原理
- 父元素设置
DataContext - 子元素自动继承
- 绑定自动去这里找数据
示例
后台
1 public class Student 2 { 3 public string Name { get; set; } = "张三"; 4 } 5 6 // 窗口 7 this.DataContext = new Student();
界面
1 <TextBlock Text="{Binding Name}" />
特点
✅ MVVM 架构核心
✅ 自动继承
✅ 最简洁、最常用
四、数据源 2:ElementName(控件绑定控件)
作用
把另一个界面元素当作数据源。
语法
1 {Binding ElementName=控件名, Path=属性名}
示例
输入框文字 → 同步到 TextBlock
1 <TextBox x:Name="txtInput" /> 2 <TextBlock Text="{Binding ElementName=txtInput, Path=Text}" />
适用场景
- 滑块控制大小
- 勾选框控制启用
- 输入框实时显示
- 纯界面联动
五、数据源 3:RelativeSource(相对数据源,超级重要)
作用
相对于自己 / 父元素 / 模板父级 找数据源。
不用 Name,纯靠相对位置绑定。
不用 Name,纯靠相对位置绑定。
4 种模式
1. 绑定到自己(Self)
1 Width="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"
2. 绑定到父控件(FindAncestor)
控件模板必备!
1 {TemplateBinding Background} 2 等价于 3 {Binding Background, RelativeSource={RelativeSource TemplatedParent}}
4. 模板内绑定到父模板(Mode=PreviousData)
极少用
适用场景
✅ 控件模板
✅ 样式模板
✅ 无法使用 ElementName 的场景
六、数据源 4:Source(直接指定数据源)
作用
直接给绑定指定一个数据源:
- 资源
- 静态对象
- 图片路径
- 独立对象
用法 1:绑定到资源
1 <Window.Resources> 2 <local:Student x:Key="MyStudent" Name="李四"/> 3 </Window.Resources> 4 5 <TextBlock Text="{Binding Name, Source={StaticResource MyStudent}}" />
用法 2:直接绑定静态对象
1 Text="{Binding Name, Source={x:Static local:MyClass.StudentInstance}}"
适用场景
✅ 资源绑定
✅ 静态数据
✅ 独立数据源
七、数据源 5:.NET 对象 / 集合(后台数据)
作用
把后台类、对象、集合当作数据源(MVVM)。
1. 普通对象
1 public Student MyStudent { get; set; } = new Student();
2. 集合(必须用 ObservableCollection)
1 public ObservableCollection<Student> Students { get; set; }
绑定
1 <ListBox ItemsSource="{Binding Students}" />
适用场景
✅ 业务数据
✅ 列表显示
✅ MVVM
八、5 大数据源 超级对比表(必背)
1 数据源 语法 来源 最常用场景 2 DataContext {Binding Name} 上下文对象 MVVM、全局数据 3 ElementName ElementName=xxx 界面控件 控件联动 4 RelativeSource RelativeSource=... 自身 / 父元素 模板、样式 5 Source Source=... 资源 / 静态 独立数据 6 .NET 对象 {Binding 集合} 后台数据 业务列表
九、数据源优先级(重要)
如果同时指定多个,优先级如下:
- ElementName
- Source
- RelativeSource
- DataContext(默认最低)
十、最经典综合示例(3 种数据源一起用)
1 <!-- 1. DataContext 数据源 --> 2 <Window DataContext="{StaticResource MyVM}"> 3 <Grid> 4 <!-- 2. ElementName 数据源 --> 5 <TextBox x:Name="txt" /> 6 7 <!-- 3. RelativeSource 数据源 --> 8 <TextBlock 9 Text="{Binding Text, ElementName=txt}" 10 Width="{Binding ActualWidth, RelativeSource={RelativeSource Self}}" 11 DataContext="{StaticResource MyStudent}" /> 12 </Grid> 13 </Window>
十一、最终总结(1 分钟彻底记住)
WPF 绑定数据源 = 5 种
- DataContext(默认,最常用)
- ElementName(控件绑定控件)
- RelativeSource(相对位置 / 模板)
- Source(直接指定资源)
- .NET 对象 / 集合(后台数据)
一句话记住
数据找 DataContext,控件找 ElementName,模板找 RelativeSource!
浙公网安备 33010602011771号