TemplateBinding和Binding有什么区别

 

TemplateBindingBinding的一个轻量级版本,它失去了成熟版本Binding的很多功能,比如继承内容引用(inheritence context referencing),RelativeSource引用,还有通过IValueConverter/TypeConverter机制的动态类型转换。它仅支持由模板产生的FrameworkElements,它的数据源引用会指向模板中的父级元素。TemplateBinding最主要的用途是内置在模板中绑定模板化元素的属性,在这种情况下,比起成熟Binding效率要高得多。

下面两个绑定效果是一样的

<TextBlock Text="{TemplateBinding MyText}"/>

<TextBlock Text="{Binding Path=MyText, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}"/>
 

除上面之外,Binding还支持以下的绑定

有把目标对象绑定到和目标对象自身有相关关系的对象上,这时就需要用到相对数据源扩展。例如:

 
 
  1. <Window x:Class="Yingbao.Chapter2.RelativeEx.AppWin"   
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  4.     Title="相对绑定" Height="100" Width="300">    
  5.     <StackPanel Orientation="Horizontal"    
  6.                 HorizontalAlignment="Center">   
  7.         <TextBlock FontSize="20" Text="{Binding       
  8.              RelativeSource={RelativeSource self}, Path=FontSize}"/>           
  9.         <TextBlock Margin="10,1,1,5"  FontSize="20" Text="{Binding    
  10.             RelativeSource={RelativeSource AncestorType={x:Type    
  11.             StackPanel}}, Path=Orientation}"/>                           
  12.     </StackPanel>   
  13. </Window>  

在这个例子中,笔者使用了两个相对数据源扩展,第一个TextBlock的Text绑定到自身的字体大小上;第二个TextBlock的Text则绑定到其父节点StackPanel的Orientation属性上。这段XAML的运行结果如图2-5所示。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值