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

相关推荐
量子物理学3 小时前
Modbus TCP
c#·modbus tcp
尤老师FPGA3 小时前
使用ZYNQ芯片和LVGL框架实现用户高刷新UI设计系列教程(第四十五讲)
android·java·ui
人工智能AI技术4 小时前
能用C#开发AI吗?
人工智能·c#
自己的九又四分之三站台7 小时前
6. 简单将原生代码改为流式请求
c#
一叶星殇9 小时前
C# .NET 如何解决跨域(CORS)
开发语言·前端·c#·.net
JQLvopkk9 小时前
C#调用Unity实现设备仿真开发浅述
开发语言·unity·c#
zxy284722530110 小时前
使用Topshelf部署window后台服务(C#)
c#·安装·topshelf·后台服务
CodeCraft Studio11 小时前
从框架到体验:Qt + Qtitan 构建制造业嵌入式UI整体解决方案
开发语言·qt·ui·gui·嵌入式开发·hmi·制造业嵌入式ui
AI_零食11 小时前
鸿蒙的flutter框架表达:生命律动系统
学习·flutter·ui·华为·harmonyos·鸿蒙
AI_零食11 小时前
鸿蒙跨端框架 Flutter 学习 Day 6:Future 在 UI 渲染中的心跳逻辑
学习·flutter·ui·华为·harmonyos·鸿蒙