随笔 - 2  文章 - 0 评论 - 0 阅读 - 191
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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"/>
复制代码

 

posted on   月夜幽  阅读(184)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示