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

相关推荐
软件黑马王子16 分钟前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
水煮庄周鱼鱼5 小时前
C# 入门简介
开发语言·c#
软件黑马王子6 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Nicole Potter7 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
code_shenbing7 小时前
WPF实现打印机控制及打印
wpf
gu208 小时前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
小盼江10 小时前
水果生鲜农产品推荐系统 协同过滤余弦函数推荐水果生鲜农产品 Springboot Vue Element-UI前后端分离 代码+开发文档+视频教程
vue.js·spring boot·ui
pchmi12 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#
yuanpan13 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
滴_咕噜咕噜14 小时前
C#基础总结:常用的数据结构
开发语言·数据结构·c#