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.运行结果

相关推荐
top_designer1 小时前
Firefly 样式参考:AI 驱动的 UI 资产“无限”生成
前端·人工智能·ui·aigc·ux·设计师
用户8356290780512 小时前
C# 自动化生成 PowerPoint 演示文稿
后端·c#
饮品爱好者2 小时前
[C#] NO.4 我的第一个项目
vscode·职场和发展·c#·github
Macbethad3 小时前
使用WPF编写一个读取串口的程序
wpf
专注VB编程开发20年4 小时前
.net按地址动态调用VC++DLL将非托管DLL中的函数地址转换为.NET可调用的委托
开发语言·c++·c#·.net
玩泥巴的6 小时前
.NET驾驭Excel之力:工作簿与工作表操作基础
c#·excel·二次开发·office·com互操作
czhc11400756636 小时前
C# 1116 流程控制 常量
开发语言·c#
葛小白16 小时前
C#进阶12:C#全局路径规划算法_Dijkstra
算法·c#·dijkstra算法
yivifu7 小时前
精益求精,支持处理嵌套表格的Word表格转HTML表格
开发语言·c#·word
唐青枫8 小时前
C#.NET 全局异常到底怎么做?最完整的实战指南
c#·.net