十分钟带你搞懂WPF模板Template

发布时间 2023-10-13 19:22:27作者: Aatrox1

三类模板(ControlTemplate,DataTemplate,ItemsPanelTemplate )

ControlTemplate(所有控件的显示渲染)

是用来重写现有控件的可视结构的,一般和依赖属性和附加属性结合,加上绑定,控件可以获得很好的扩展。

demo

以下是一个简单的WPF ControlTemplate样式示例。这个示例是为一个Button控件定义的样式。

<Window.Resources>  
    <Style TargetType="Button">  
        <Setter Property="Template">  
            <Setter.Value>  
                <ControlTemplate TargetType="Button">  
                    <Border Name="Border"   
                           BorderBrush="Black"   
                           BorderThickness="1"   
                           Background="{TemplateBinding Background}"   
                           Padding="5">  
                        <ContentPresenter Content="{TemplateBinding Content}"   
                                          ContentTemplate="{TemplateBinding ContentTemplate}"   
                                          HorizontalAlignment="Center"   
                                          VerticalAlignment="Center"/>  
                    </Border>  
                </ControlTemplate>  
            </Setter.Value>  
        </Setter>  
    </Style>  
</Window.Resources>  
  
<Grid>  
    <Button Content="Hello, World!" />  
</Grid>

这个样式中,我们创建了一个新的ControlTemplate,为Button控件定义了一个新的外观。这个模板包含一个Border,我们设置了一些其属性,如背景色、边框颜色和边框宽度。然后,我们添加了一个ContentPresenter,用于显示Button的Content。

在XAML中使用这个样式,只需要将样式应用到任何Button控件即可。在这个例子中,我们直接在Grid中创建了一个Button,它会自动应用这个样式。

DataTemplate(数据集合呈现控制)ListBox

概念:用于定义数据对象的可视化结构的。将数据集合绑定给控件
用途:用于数据集合控件:ItemsControl,ListBox,ListView,DataGrid

demo

以下是一个简单的WPF DataTemplate示例。这个示例是为一个具有自定义数据对象(例如名为“Person”)的控件定义的样式。

<Window.Resources>  
    <DataTemplate x:Key="PersonDataTemplate">  
        <StackPanel>  
            <TextBlock Text="{Binding Name}" FontWeight="Bold" />  
            <TextBlock Text=" (" />  
            <TextBlock Text="{Binding Age}" FontSize="smaller" />  
            <TextBlock Text=")" />  
        </StackPanel>  
    </DataTemplate>  
</Window.Resources>  
  
<Grid>  
    <ListBox ItemsSource="{Binding Persons}" ItemTemplate="{StaticResource PersonDataTemplate}" />  
</Grid>

在ListBox控件中,我们通过设置“ItemsSource”属性来绑定一个Persons集合,并通过设置“ItemTemplate”属性来应用我们之前定义的“PersonDataTemplate”。这样,ListBox将会自动根据PersonDataTemplate展示每个Person对象的数据。

ItemsPanelTemplate 容器模板(数据集合排列控件)

ItemsPanelTemplate可以用来定义集合控件的容器外观。ListBox的每一项的排列方式是遵循StackPanel的
原则,也就是从上到下的排列方式。如果要实现从左到右排列.ComboBox默认是竖直排列的,我们要横着排列,只需要定义ItemsPanel为WrapPanel,就可以了。

关注我,WPF FlyUI框架作者
github地址:https://github.com/AatroxBot/FlyUI.Demo.git
码云地址:https://gitee.com/Aatrox1/fly-ui-demo.git