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所示。

 

你可能感兴趣的:(Class,扩展,Path,binding)