接上篇,
我們來看一看Elementname,Source,RelativeSource 三種綁定的方式
1.ElementName顧名思義就是根據Ui元素的Name來進行綁定:
例子:
<Window x:Name="MainWindow">
<Grid>
<Button Background=”{Binding ElementName=MainWindow, Path=Background}”/>
</Grid>
</Window>
效果等同於
<Window>
<Grid>
<Button Background=”{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window},Path=Background}”/>
</Grid>
</Window>
區別:
ElementName屬性用於引用一個UI對象的名稱,其的作用域在同一XAML文件內,不能引用另一XAML文件的某個Ui元素名。
2.Source屬性用於指定對象綁定路徑的引用。 其特點是:Source屬性通常用於綁定設置的對象時,是已知的。
<Window x:Name="MainWindow">
<Grid>
<Button Background=”{Binding Source={StaticResource ButtonStyle}}”/>
</Grid>
</Window>
3.RelativeSource
在不確定綁定的Source時,但知道與綁定對象兩者相對關系時就需要使用RelativeSource,這也是RelativeSource 與ElementName和Source的最大區別。
RelativeSource 的三種典型用法:
/1.UI元素的一個屬性綁定在自身的另一個屬性上
<Label Background = {Binding Path=Forgroud, RelativeSource={RelativeSource Self}} />
/2.UI元素的一個屬性綁定在某個父元素的屬性上
<Grid>
<Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/>
</Grid>
/3.Template中的元素的屬性綁定在Template使用者元素的屬性上
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
例子:
<Style TargetType="{x:Type local:NumericUpDown}">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:NumericUpDown}">
<Grid Margin="3">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border BorderThickness="1" BorderBrush="Gray"
Margin="2" Grid.RowSpan="2"
VerticalAlignment="Center" HorizontalAlignment="Stretch"><TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value}"
Width="60" TextAlignment="Right" Padding="5"/>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
利用TemplateBinding 綁定模板與原對象之間的屬性
{TemplateBinding Path=PathToProperty}
例子:
<ControlTemplate TargetType="{x:Type Button}" x:Key="buttonTemp">
<Border BorderThickness="3" Background="{TemplateBinding Foreground}">
<TextBlock Foreground="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
轉載時,請注明本文來源:www.cnblogs.com/tmywu
作者: 淘米部落
mail:tommywu23@126.com