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 2023-08-30 00:18  月夜幽  阅读(83)  评论(0编辑  收藏  举报