1.模板绑定TemplateBindingide
什么状况下使用模板绑定?工具
--当您仍可能想要使用公共属性更改控件的外观时,模板绑定是您的不二之选学习
怎么使用模板绑定?spa
--咱们还以学习笔记一中的Button为例,自定义模板中的Border的Background=“Red”,使用TemplateBinding则为Background=“{TemplateBinding Backbround}”;code
等号左边的Background为Border的背景颜色,等号右边的Background为Button的属性。blog
使用模板绑定可以解决什么样的问题?get
--当多个按钮呈现的可视化结构相同,只是背景颜色或是边框颜色不同时,若是不使用TemplateBinding,可能您就要为每个按钮定义一个控件模板,这些控件模板相差的it
也许只是一个属性。因此为了解决这种状况咱们能够使用TemplateBinding,示例以下:event
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}"> <Border Name="Border" BorderBrush="Orange" BorderThickness="3" CornerRadius="2" Background="{TemplateBinding Background}" TextBlock.Foreground="White" SnapsToDevicePixels="True"> <Grid> <Rectangle Name="FocusCue" Visibility="Hidden" Stroke="Black" StrokeThickness="1" StrokeDashArray="1 2" SnapsToDevicePixels="True"></Rectangle> <ContentPresenter RecognizesAccessKey="True" Margin="{TemplateBinding Padding}"></ContentPresenter> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="Border" Property="Background" Value="DarkRed" /> </Trigger> <Trigger Property="IsPressed" Value="true"> <Setter TargetName="Border" Property="Background" Value="IndianRed" /> <Setter TargetName="Border" Property="BorderBrush" Value="DarkKhaki" /> </Trigger> <Trigger Property="IsKeyboardFocused" Value="True"> <Setter TargetName="FocusCue" Property="Visibility" Value="Visible" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate>
<Button Content="ButtonA" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Background="Red" Template="{StaticResource ButtonTemplate}" /> <Button Content="ButtonB" HorizontalAlignment="Left" Margin="10,47,0,0" VerticalAlignment="Top" Width="75" Background="Green" Template="{StaticResource ButtonTemplate}" />
效果如图:模板
2.自动应用模板
自动应用模板是不设置Template=“{StaticResource ButtonTemplate}”时,项目中的按钮自动应用定义好的控件模板。
怎么实现自动应用模板?
--技巧是使用类型样式,这种样式会自动影响相应的元素类型并设置Template属性,示例以下:
<Style TargetType="{x:Type Button}"> <Setter Property="Control.Template" Value="{StaticResource ButtonTemplate}" /> </Style>
注:虽然在Resources里定义,可是没有定义x:Key属性。其中的ButtonTemplate为学习笔记一中定义的控件模板
<Button Content="ButtonA" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" /> <Button Content="ButtonB" HorizontalAlignment="Left" Margin="10,75,0,0" VerticalAlignment="Top" Width="75" />
效果如图:,其实从工具箱里新添加一个按钮也会自动应用该控件模板,只是如今我还不会制做和上传Gif类型的文件,没办法贴效果图。