TemplateBinding和Binding

TemplateBinding是Binding的一个轻量级版本,它失去了成熟版本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还支持以下的绑定

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

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

在这个例子中,笔者使用了两个相对数据源扩展,第一个TextBlock的Text绑定到自身的字体大小上;第二个TextBlock的Text则绑定到其父节点StackPanel的Orientation属性上。

原文地址:https://www.cnblogs.com/sekon/p/4644481.html