Article directory
Article collection address
WPF price control template
What problem is the control template used to solve? Problem with duplicate nested page elements.
For example, I have written a page element
<Button Width="100">
<TextBox Text="我是TextBox"></TextBox>
</Button>
I have many buttons with this style, I have to repeat this code many times
<Button Width="100" Height="30">
<TextBox Text="我是TextBox"></TextBox>
</Button>
<Button Width="100"
Height="30">
<TextBox Text="我是TextBox"></TextBox>
</Button>
<Button Width="100"
Height="30">
<TextBox Text="我是TextBox"></TextBox>
</Button>
<Button Width="100"
Height="30">
<TextBox Text="我是TextBox"></TextBox>
</Button>
<Button Width="100"
Height="30">
<TextBox Text="我是TextBox"></TextBox>
</Button>
Control templates are designed to solve the problem of repeatedly declaring nested control elements.
We create a new Button button
<Button Content="正常按钮"
Width="100"
Height="30" />
Then we can see a copy of the default button written by Microsoft
Simply put, why the button looks like this is all set through the template
Look at this button, the border is black, and the text is centered, all of which are set.
There is no need to understand too much, I will write a control template button here
<Window.Resources>
<!--设置控件模版-->
<ControlTemplate x:Key="defaultButtonTemplate"
TargetType="Button">
<!--在这里相当于重新写了Button按钮,Button按钮的属性-->
<Border Background="red"
CornerRadius="5">
<StackPanel Orientation="Horizontal">
<TextBlock Text="❥"
VerticalAlignment="Center" />
<!--这个是原本Button按钮的Content的属性,不添加就不显示Button了-->
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
VerticalAlignment="{TemplateBinding VerticalAlignment}" />
</StackPanel>
</Border>
</ControlTemplate>
</Window.Resources>
<Grid>
<StackPanel>
<Button Content="控件按钮"
Width="100"
Height="30"
Template="{StaticResource defaultButtonTemplate}"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
<Button Content="正常按钮"
Width="100"
Height="30" />
</StackPanel>
</Grid>
</Window>
Realize the effect: