DataContext和ItemSource
2024-08-28 07:46:05
一对多的关系
DataContext为上下文,绑定数据源
ItemSource取上下文中的某属性,会一级一级往上找属性
一般ItemSource的绑定,绑定到Grid/DataGrid一类容器上,底下的控件到这一级找
对比
1.DataContext 一般是一个非集合性质的对象,而ItemSource 更期望数据源是集合对象
2.DataContext 是 FrameworkElement 类中定义的一个依赖属性(Dependency property),ItemsSource是 在ItemsControl 类中定义的。所有继承自FrameworkElement 的类(控件)都可以使用DataContext属性并给其赋值,但我们只能给ItemsSource赋值为集合对象
3.DataContext不能产生模板,它只能用来筛选出数据,供其它控件来绑定。而ItemsSource主要作用就是给模板提供数据
4.DataContext主要用来抓取一些子元素需要使用的数据,以保证子元素能够顺利的使用数据。ItemsSource不会用来分享数据,它只是对定义好的元素有效
举例
后台
public partial class DataContextAndItemSource : Window
{
public DataContextAndItemSource()
{
InitializeComponent();
ObservableCollection<Student> students = new ObservableCollection<Student>();
students.Add(new Student()
{
Age = 15,
Name = "吴芳",
Sex = "女"
});
students.Add(new Student()
{
Age = 16,
Name = "刘洋",
Sex = "男"
});
//给DataContextAndItemSource的DataContext赋值
DataContext = students;
}
}
前端
<!--ItemsSource绑定后台DataContext的数据-->
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" CanUserAddRows="False" IsEnabled="False">
<DataGrid.Columns>
<DataGridTextColumn Width="*" Binding="{Binding Name}" Header="名称" />
<DataGridTextColumn Width="*" Binding="{Binding Age}" Header="年龄" />
</DataGrid.Columns>
</DataGrid>
示例代码
https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/DataContextAndItemSource
最新文章
- IP地址,子网掩码,默认网关,DNS服务器知识详解(转)
- LintCode Longest Common Subsequence
- Node.js Express 框架
- 深入浅出REST
- mobile touch事件
- 【iCore3 双核心板】例程十三:SDIO实验——读取SD卡信息
- MyBatis学习总结_05_实现关联表查询
- 我的javascript学习之路(一)对象之基础
- JSF HelloWord
- Codeforces Bubble Cup 8 - Finals [Online Mirror]H. Bots 数学
- OSG-3.4.0 简要说明(Readme)
- @Index用法——javax.persistence.Index
- word-break与word-wrap
- linker command failed with exit code 1 (use -v to see invocation),经典Xcode编译错误的出现和解决!
- JavaScript函数节流与函数去抖
- Ubuntu安装Mysql过程及远程问题解决
- Tomcat 虚拟目录映射
- cocos2d-x3.x Vector
- 网络编程基础【day09】:socketserver进阶(十)
- flutter环境配置
热门文章
- 序列 mysql
- 使用DOT语言和Graphviz绘图(翻译)
- 某整形数组中除了两个单身整数外, 其余的整数都是成对出现的, 利用C/C++代码求出这两个单身整数。 要求: 时间复杂度o(n), 空间复杂度o(1)------某公司招聘试题
- mysqlsla安装
- iOS BCD编码
- ActivityManagerService的启动过程
- METHODS OF AND APPARATUS FOR USING TEXTURES IN GRAPHICS PROCESSING SYSTEMS
- 【codeforces 534C】Polycarpus' Dice
- bootstrap paginator使用简述
- 获取全局上下文(getApplicationContext)_创建Shared Preference工具类_实现自动登录