ContentTemplate:
<Button.ContentTemplate> <DataTemplate> <StackPanel> <TextBlock Text="The time is:" TextAlignment="Center" /> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <TextBlock Text="{Binding Hour}" /> <TextBlock Text=":" /> <TextBlock Text="{Binding Minute}" /> <TextBlock Text=":" /> <TextBlock Text="{Binding Second}" /> </StackPanel> </StackPanel> </DataTemplate> </Button.ContentTemplate>
Button内部有public DataTemplate ContentTemplate { get; set; }
既实例化一个DataTemplate然后赋值为Button的ContentTemplate字段
<phone:PhoneApplicationPage.Resources> <DataTemplate x:Key="brushTemplate"> <Ellipse Width="100" Height="100" Fill="{Binding}" /> </DataTemplate> </phone:PhoneApplicationPage.Resources> <Button HorizontalAlignment="Center" ContentTemplate="{StaticResource brushTemplate}"> <RadialGradientBrush> <GradientStop Offset="0" Color="Blue" /> <GradientStop Offset="1" Color="AliceBlue" /> </RadialGradientBrush> </Button>
通过{Binding}可以直接绑定UIElement的Content,所以出现了上面的情况
更加复杂的情况如下:
<Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Click="OnButtonClick"> <Button.Content> <petzold:Clock /> </Button.Content> <Button.ContentTemplate> <DataTemplate> <StackPanel> <TextBlock Text="The time is:" TextAlignment="Center" /> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <TextBlock Text="{Binding Hour}" /> <TextBlock Text=":" /> <TextBlock Text="{Binding Minute}" /> <TextBlock Text=":" /> <TextBlock Text="{Binding Second}" /> </StackPanel> </StackPanel> </DataTemplate> </Button.ContentTemplate> </Button>
ControlTemplate:
<ControlTemplate x:Key="btnTemplate" TargetType="Button"></ControlTemplate>
TemplateBinding:
<Button Content="Click me!" HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="{StaticResource PhoneAccentBrush}" BorderThickness="6"> <Button.Template> <ControlTemplate TargetType="Button"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <TextBlock Text="temporary" /> </Border> </ControlTemplate> </Button.Template> </Button>
绑定控件的自带属性,ControlTemplate的特殊绑定模式
ContentPresenter:
<ControlTemplate TargetType="Button"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="12"> <ContentPresenter Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" /> </Border> </ControlTemplate>