模板绑定

模板绑定 : 通过使用模板绑定,模板可以从应用模板的控件中提取一个值。

<Window x:Class="TemplateDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
<Border BorderBrush="#696A6B" BorderThickness="1" Background="Gray" TextBlock.Foreground="White">
<ContentPresenter RecognizesAccessKey="True" Margin="{TemplateBinding Padding}"></ContentPresenter>
</Border>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<Button Margin="10" Padding="5" Template="{StaticResource ButtonTemplate}">
A Simple Button with a Custom Template
</Button>
</StackPanel>
</Window>

 代码2 :

结果:

<Window x:Class="TemplateDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
<Border Name="Border" BorderBrush="#696A6B" BorderThickness="1" Background="Gray" TextBlock.Foreground="White">
<Grid>
<Rectangle Name="FocusCus" 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="FocusCus" Property="Visibility" Value="Visible"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<Button Margin="10" Padding="5" Template="{StaticResource ButtonTemplate}">
A Simple Button with a Custom Template
</Button>
</StackPanel>
</Window>

原文地址:https://www.cnblogs.com/gylhaut/p/5439796.html