前言
我们在开发wpf程序的过程中,为了提高代码的重复利用率,经常会使用模板技术,本文就是介绍ControlTemplate中的ContentPresenter的作用。
1、ContentPresenter放置于中
1.1 创建模板
ContentPresenter常用于ControlTemplate中,它表示占位符,比如下面的代码中建立了一个模板,该模板中含有一个Border ,这个边框控件设置为红色,变宽厚度为10,并在其中放置了一个ContentPresenter ,并指定该控件代表的内容也就是Buttton的Content内容水平居中,垂直居中。
<Window x:Class="wpf之controlTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:wpf之controlTemplate"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ControlTemplate x:Key="btn_temp" TargetType="{x:Type Button}">
<Border BorderBrush="Red" BorderThickness="10" Background="{TemplateBinding Background }" >
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<Button Height="300" Content="按钮" Background="Blue" Template="{StaticResource btn_temp}"/>
</StackPanel>
</Window>
1.2 使用模板
最终在Window窗体中放置一个StackPanel,StackPanel中放置一个Button,由于该Button使用了模板btn_temp,所以在中间显示了Button的Content属性。
2、ContentPresenter放置于Grid中
2.1 创建模板
ContentPresenter常用于ControlTemplate中,它表示占位符,比如下面的代码中建立了一个模板,该模板中含有一个Grid,这个Grid有两行,第一行高度为100,第二行占用剩余所有高度,其中第一行放置了一个椭圆控件Ellipse ,并指定椭圆的填充色与使用该模板的控件的背景色相同;第2行放置了一个ContentPresenter ,并指定该控件代表的内容也就是Buttton的Content内容水平居中,垂直居中。
<Window x:Class="wpf之controlTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:wpf之controlTemplate"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<ControlTemplate x:Key="btn_temp" TargetType="{x:Type Button}">
<Grid >
<Grid.RowDefinitions >
<RowDefinition Height=" 100"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions >
<Ellipse Grid.Row="0" Name="ellipse" Fill="{TemplateBinding Background}"/>
<ContentPresenter Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Window.Resources>
<StackPanel>
<Button Height="300" Content="圆形按钮" Background="Blue" Template="{StaticResource btn_temp}"/>
</StackPanel>
</Window>
2.2 使用模板
最终在Window窗体中放置一个StackPanel,StackPanel中放置一个Button,由于该Button使用了模板btn_temp,所以分为上下两部分,上部分是一个椭圆,下部分显示了Button的Content属性。
马工撰写的年入30万+C#上位机项目实战必备教程(点击下方链接即可访问文章目录)
1、《C#串口通信从入门到精通》
2、《C#与PLC通信从入门到精通 》
3、《C# Modbus通信从入门到精通》
4、《C#Socket通信从入门到精通 》
5、《C# MES通信从入门到精通》
6、《winform控件从入门到精通》
7、《C#操作MySql数据库从入门到精通》