c# wpf template itemtemplate+ListBox

1.概要

2.代码

复制代码
<Window x:Class="WpfApp2.Window7"
        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:WpfApp2"
        mc:Ignorable="d"
        Title="Window7" Name="win" Height="450" Width="800">
    <Window.Resources>
        <DataTemplate x:Key="MyDataTemplate">
            <StackPanel Orientation="Horizontal">
                <Border Background="Pink">
                    <TextBlock Text="{Binding Title}"/>
                </Border>
                <Button Content="{Binding Author}"  Cursor="Hand" Margin="10,0"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox Name="l1" Grid.Row="1" ItemsSource="{Binding BookList,ElementName=win}" ItemTemplate="{StaticResource MyDataTemplate}"/>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp2
{
    /// <summary>
    /// Window7.xaml 的交互逻辑
    /// </summary>
    public partial class Window7 : Window
    {
        public Window7()
        {
            InitializeComponent();
            BookList.Add(new Book() { Title = "三国演义", Author = "罗贯中", Time = DateTime.Now.AddYears(-200) });
            BookList.Add(new Book() { Title = "红楼梦", Author = "曹雪芹", Time = DateTime.Now.AddYears(-150) });
            BookList.Add(new Book() { Title = "西游记", Author = "吴承恩", Time = DateTime.Now.AddYears(-230) });
            //l1.ItemsSource = BookList;
        }
        public List<Book> BookList { get; set; } = new List<Book>();
    }
}

public class Book

{

public required string Title { get; set; }

public required string Author { get; set; }

public DateTime Time { get; set; }

}

3.运行结果

相关推荐
我是唐青枫8 小时前
C#.NET 索引器完全解析:语法、场景与最佳实践
c#·.net
FuckPatience12 小时前
C# 使用内存映射文件实现进程间通信
c#
kylezhao201914 小时前
如何在 C# 项目中使用 NLog 进行日志记录
开发语言·c#
UI设计兰亭妙微14 小时前
兰亭妙微ui设计公司分享:移动端界面用户友好型设计的核心思路
ui·移动端界面设计
小菱形_16 小时前
【C#】IEnumerable
开发语言·c#
爱敲点代码的小哥16 小时前
Directoy文件夹操作对象 、StreamReader和StreamWriter 和BufferedStream
开发语言·c#
青稞社区.16 小时前
小米大模型 Plus 团队提出BTL-UI:基于直觉-思考-关联的GUI Agent推理
人工智能·ui
weixin_5316518117 小时前
@clack/prompts 命令行终端中构建交互式用户界面
ui
CodeCraft Studio17 小时前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建折线图
java·c#·excel·aspose.cells·excel图表·excel api库·excel折线图
m5655bj17 小时前
C# 在 PDF 文档中添加电子签名
开发语言·pdf·c#