ContentPresenter 保留原控件属性TemplateBinding Padding,即绑定每个CheckBox自己的Margin,更灵活
此时,点击Rectangle是没有效果的
Setter可以选择TargetName,即一个控件的触发器可以修改另一个控件的属性
Brush一类画笔,需定义为对象才能使用可以使用颜色、图片等等
<Window.Resources> <ControlTemplate x:Key="CheckBoxControlTemplate" TargetType="CheckBox"> <ControlTemplate.Resources> <!--颜色--> <SolidColorBrush x:Key="ColorBrush" Color="Pink"></SolidColorBrush> <!--图片--> <ImageBrush x:Key="ImageBrush" ImageSource="Images/cat.jpg"></ImageBrush> </ControlTemplate.Resources> <StackPanel> <Rectangle Name="breakRectangle" Stroke="OrangeRed" StrokeThickness="2" Width="100" Height="100"> <Rectangle.Fill> <!--默认Rectangle填充色为White--> <SolidColorBrush Color="White"></SolidColorBrush> </Rectangle.Fill> </Rectangle> <!--ContentPresenter 保留原控件属性--> <ContentPresenter Margin="{TemplateBinding Padding}"></ContentPresenter> </StackPanel> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter TargetName="breakRectangle" Property="Fill" Value="{StaticResource ImageBrush}"></Setter> </Trigger> <Trigger Property="IsChecked" Value="False"> <Setter TargetName="breakRectangle" Property="Fill" Value="{StaticResource ColorBrush}"></Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="0.5*"></RowDefinition> <RowDefinition Height="0.5*"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <Label Grid.Row="0" Content="没有选中时,CheckBox填充色为Pink"></Label> <Label Grid.Row="1" Content="选中时,CheckBox填充为猫猫的图片"></Label> <CheckBox Grid.Row="2" Template="{StaticResource CheckBoxControlTemplate}" Content="我是模板CheckBox"></CheckBox> </Grid>
https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Template/StyleUseTemplate
对非内置属性的修改,用模板用style识别不了textBlock1直接写CheckBox 的Triggers识别不了IsChecked
https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Template/ControlTemplate
转载于:https://www.cnblogs.com/Lulus/p/8157711.html
相关资源:ControlTemplateBrowser.rar