wpf DataTemplate 和 ControlTemplate 区别,应用举例

在WPF中,模版(ControlTemplate ) ControlTemplate用于定义控件的内部结构和外观,它决定了控件的"长成什么样子",并允许开发者在控件原有的内部逻辑基础上扩展自己的逻辑。DataTemplate则专注于数据内容的展示方式,即数据如何被可视化呈现。

cs 复制代码
示例实现
1. 定义歌曲类
首先,我们定义一个Song类,用于表示歌曲数据。

public class Song  
{  
    public string Title { get; set; }  
    public string Artist { get; set; }  
    // 可以添加更多属性,如专辑、时长等  
}
2. 创建DataTemplate
在XAML中,我们为Song类创建一个DataTemplate,用于定义每首歌曲在播放列表中的显示方式。

<Window.Resources>  
    <DataTemplate x:Key="SongDataTemplate">  
        <StackPanel Orientation="Horizontal" Margin="5">  
            <TextBlock Text="{Binding Title}" FontSize="16" FontWeight="Bold"/>  
            <TextBlock Text=" - " Margin="2,0,0,0"/>  
            <TextBlock Text="{Binding Artist}" FontSize="14"/>  
        </StackPanel>  
    </DataTemplate>  
</Window.Resources>


3. 创建ControlTemplate
接下来,我们为播放列表控件(例如ListBox)创建一个ControlTemplate,以改变其整体外观。这里为了简化,我们只改变背景色和滚动条样式,但你可以根据需要添加更多自定义内容
<Window.Resources>  
    <!-- 之前的DataTemplate定义 -->  
  
    <ControlTemplate x:Key="PlaylistControlTemplate" TargetType="ListBox">  
        <Border Background="LightGray" Padding="10">  
            <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">  
                <ItemsPresenter/>  
            </ScrollViewer>  
        </Border>  
    </ControlTemplate>  
</Window.Resources>

4. 应用Template
现在,我们在XAML布局中应用这两个模版。首先,为ListBox设置ControlTemplate,然后为其ItemTemplate设置之前定义的DataTemplate。
<Grid>  
    <ListBox x:Name="PlaylistListBox"  
             Template="{StaticResource PlaylistControlTemplate}"  
             ItemTemplate="{StaticResource SongDataTemplate}">  
        <!-- 这里通过数据绑定填充歌曲列表 -->  
    </ListBox>  
</Grid>
相关推荐
@淡 定1 天前
分布式事务解决方案
分布式·wpf
棉晗榜1 天前
WPF将程序集里面嵌入的资源文件下载到本机磁盘中,将项目中的文件下载到桌面
开发语言·wpf
△曉風殘月〆1 天前
WPF MVVM实战系列教程(一、Prism框架介绍)
wpf·mvvm·prism
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(三)?
wpf·界面控件·devexpress·ui开发·.net 10
△曉風殘月〆1 天前
WPF MVVM实战系列教程(二、使用Visual Studio 创建Prism项目)
wpf·mvvm·prism
bugcome_com4 天前
WPF 核心布局控件全解析:从 Grid 到 UniformGrid 的实战应用
c#·wpf
观无4 天前
WPF-Datagrid控件的无缝滚动
wpf
꧁༺℘₨风、凌๓༻꧂4 天前
C# WPF 项目中集成 Pdf查看器
pdf·c#·wpf
Kiyra5 天前
WebSocket vs HTTP:为什么 IM 系统选择长连接?
分布式·websocket·网络协议·http·设计模式·系统架构·wpf