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>
相关推荐
星河Cynthia20 小时前
WPF基于resx资源文件的多语言实现
c#·wpf
量子物理学20 小时前
WPF 标签预览可以显示图片运行后不显示
c#·wpf
△曉風殘月〆21 小时前
WPF Prism中的依赖注入详解
wpf·mvvm
△曉風殘月〆21 小时前
WPF Prism创建Bootstrapper/启动器
wpf·mvvm
小曹要微笑21 小时前
WPF的依赖与附加属性
wpf·依赖属性·附加属性
bugcome_com2 天前
WPF 命令 ICommand 从原理到实战
后端·wpf·icommand
武藤一雄3 天前
WPF处理耗时操作的7种方法
microsoft·c#·.net·wpf
Venom843 天前
我的 WPF Powermill 工具
wpf
一念春风4 天前
证件照制作工具(WPF C#)
c#·wpf
He BianGu5 天前
【笔记】在WPF中GiveFeedbackEventHandler的功能和应用场景详细介绍
笔记·wpf