wpf/Silverlight/wp中如何绑定模板中的属性
<Style TargetType="{x:Type TabItem}" x:Key="EditorTabItemStyle"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type TabItem}"> <Border x:Name="layout" BorderBrush="Gray" BorderThickness="1,1,1,0" Background="{TemplateBinding Background}" CornerRadius="3" Margin="2,0,2,0"> <Grid Height="20"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="25"/> </Grid.ColumnDefinitions> <TextBlock TextAlignment="Center" Text="{TemplateBinding Header}" ToolTip="{TemplateBinding ToolTip}" Tag="{TemplateBinding Tag}" Grid.Column="0" Margin="4,0,3,0" VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBlock.ContextMenu> <ContextMenu DataContext="{TemplateBinding Tag}"> <MenuItem Header="保存" Click="Save_Command" IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu},AncestorLevel=1},Path=DataContext}" > </MenuItem> <MenuItem Header="关闭" Click="Close_Command"> </MenuItem> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> <Button Content="X" Grid.Column="1" Height="8" Width="8" Margin="4,1,3,2" Tag="{TemplateBinding Header}" Click="Button_Click" Background="{x:Null}" BorderBrush="{x:Null}" VerticalAlignment="Center"> <Button.Template> <ControlTemplate > <Grid> <Rectangle> <Rectangle.Fill> <VisualBrush> <VisualBrush.Visual> <Path x:Name="btnPath" Data="M0 0L10 10M0 10L10 0" Stroke="Gray" StrokeThickness="1"/> </VisualBrush.Visual> </VisualBrush> </Rectangle.Fill> </Rectangle> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="btnPath" Property="Stroke" Value="Red"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template> </Button> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="White"/> <Setter TargetName="layout" Property="Margin" Value="2,0,2,-1.5"/> </Trigger> <Trigger Property="IsSelected" Value="false"> <Setter Property="Background" Value="LightBlue"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style>
上面实例代码展示如何将tabitem中的字段绑定到menuitem上,先通过TemplateBinding获取属性值赋值到DataContext属性,然后再通过指定的控件类型和第几个来绑定
IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu},AncestorLevel=1},Path=DataContext}" >
具体说明可以参考:
http://www.cnblogs.com/lzhp/archive/2012/09/11/2673810.html
中的2.9的说明