1 概念
- Binding类的Source属性一般用于指定某个属性绑定的源对象,需要在每个控件上都显式指定绑定源,比较繁琐。
- DataContext通常用于指定某一个控件的默认数据上下文,它会被该控件及其所有子控件继承和使用。
- 如果几个控件需要绑定到同一个源,用DataContext将更加简洁,因为不需要像Source一样为每个控件上都显式指定绑定源。
- DataContext是FrameworkElement类的属性,大部分UI控件、窗口都继承于这个类。
2 建立数据上下文
1 <Window.DataContext> 2 <local:Teacher Name="月夜幽"> 3 <local:Teacher.Contact> 4 <local:Contact City="西安" Phone="123456789"/> 5 </local:Teacher.Contact> 6 <local:Teacher.Skill> 7 <collections:ArrayList> 8 <System:String>C#</System:String> 9 <System:String>JAVA</System:String> 10 <System:String>C++</System:String> 11 <System:String>Python</System:String> 12 </collections:ArrayList> 13 </local:Teacher.Skill> 14 </local:Teacher> 15 </Window.DataContext>
3 绑定数据上下文(不需要再使用Source了)
1 <TextBox Text="{Binding Path=Name}" Margin="10" Width="300"/> 2 <TextBox Text="{Binding Path=Contact.City}" Margin="10" Width="300"/> 3 <TextBox Text="{Binding Contact.Phone}" Margin="10" Width="300"/> 4 <TextBox Text="{Binding Skill[0]}" Margin="10" Width="300"/> 5 <TextBox Text="{Binding Skill[1]}" Margin="10" Width="300"/>
4 绑定字符串
1 <!--建立DataContext资源--> 2 <Window.DataContext> 3 <System:String>我是字符串</System:String> 4 </Window.DataContext> 5 6 <绑定本身用 . > 7 <TextBox Text="{Binding Path=.}" Margin="10" Width="300"/> 8 <TextBox Text="{Binding .}" Margin="10" Width="300"/> 9 <TextBox Text="{Binding Mode=OneWay}" Margin="10" Width="300"/> 10 <!--TextBox必须指定绑定方向 TextBlock可直接使用Binding--> 11 <TextBlock Text="{Binding}" Margin="10" Width="300"/>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现