在WPF應用的開發過程中Binding是一個非常重要的部分。
在實際開發過程中Binding的不同種寫法達到的效果相同但事實是存在很大區別的。
這里將實際中碰到過的問題做下匯總記錄和理解。
1. source = {binding} 和source = {binding RelativeSource={RelativeSource self},Path=DataContext}效果相同
理解:{binding} 不設定明確的綁定的source,這樣binding就去從本控件類為開始根據可視樹的層次結構自下而上查找不為空的Datacontext屬性的值。
{binding RelativeSource={RelativeSource self},Path=DataContext}中RelativeSource self的含義為綁定的source為控件自身,這樣binding 就綁定了自身控件的Datacontext。
效果:
<StackPanel DataContext="abc">
<Label Content="{Binding}"></Label>
<Label Content="{Binding RelativeSource={RelativeSource Self},Path=DataContext}"></Label>
</StackPanel>

<StackPanel DataContext="abc">
<Label Content="{Binding}"></Label>
<Label DataContext="def" Content="{Binding RelativeSource={RelativeSource Self},Path=DataContext}"></Label>
</StackPanel>

2.在Template的Trigger中改變Template中某個樣式控件的屬性
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border>
<Label x:Name="PART_Label" Content="{TemplateBinding ContentA}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
注: <Setter TargetName="PART_Label" Property="Content" Value="{Binding Path=ContentB, RelativeSource={RelativeSource TemplatedParent}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
當然把注:的這句改成<Setter TargetName="PART_Label" Property="Content" Value="{Binding Path=ContentB, RelativeSource={RelativeSource AncestorType={x:Type Button}}}">效果一樣。
先寫到這,下篇繼續關注Binding中ElementName,RelativeSource,Source的相同點和區別。
轉載時,請注明本文來源:www.cnblogs.com/tmywu
作者: 淘米部落
mail:tommywu23@126.com
