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>
相关推荐
samble20 小时前
从零搭建半导体设备上位机(十二):参数设置页,表单校验、范围校验与配方联动
wpf·数据校验·validationrule
samble9 天前
从零搭建半导体设备上位机(九):拖拽与交互,Adorner、DragDrop 与晶圆拖放信息
wpf·拖拽·adorner
郝学胜-神的一滴10 天前
AI 编程智能体 27:吃透MCP通信机制
人工智能·python·langchain·wpf·numpy·scikit-learn
波力海苔夹心脆67511 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
陈仓主教11 天前
# WPF CheckBox 控件详解与使用—WPF 中的控件(6)--复选框控件(CheckBox)
wpf
光泽雨13 天前
WPF 音视频四大核心方案对比
wpf·音视频
浪扼飞舟14 天前
WPF(数据绑定)
wpf
samble15 天前
从零搭建半导体设备上位机(四):单实例、启动流程与配置文件,App 里那 526 行到底在干什么
wpf·配置文件·单实例
浪扼飞舟15 天前
WPF(控件的继承树、内容控件、布局控件)
wpf
avi911118 天前
电影开源Jevdo - 源码介绍(vue版)没有android 和 没有wpf
android·wpf·框架·数据爬虫·meego·电影管理