WPF基础入门-Class3-WPF数据模板

WPF基础入门

Class3:WPF数据模板

1、先在cs文件中定义一些数据

cs 复制代码
public partial class Class_4 : Window
    {
        public Class_4()
        {
            InitializeComponent();
            List<Color> test = new List<Color>();
            test.Add(new Color() { Code = "Yellow", Name = "Red" });
            test.Add(new Color() { Code = "#00FF00", Name = "Green" });
            test.Add(new Color() { Code = "#0000FF", Name = "Blue" });
            //数据绑定到list
            list.ItemsSource = test;
        }
    }
    public class Color
    {
        public string Code { get; set;}

        public string Name { get; set; }
    }

2、xaml中编写模板

xml 复制代码
<Grid>
        <!--WPF数据模板-->
        <ListBox x:Name="list">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <!--通过Binding绑定了Background和Text 不用再业务代码cs中穿插控件操作-->
                        <Border
                            Width="10"
                            Height="10"
                            Background="{Binding Code}"></Border>
                        <TextBlock Margin="10, 0" Text="{Binding Name}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</Grid>

3、效果:

相关推荐
时光追逐者20 小时前
TIOBE 公布 C# 是 2025 年度编程语言
开发语言·c#·.net·.net core·tiobe
观无20 小时前
固高运动控制卡(GST800)基础应用分享
c#
flysh0521 小时前
如何利用 C# 内置的 Action 和 Func 委托
开发语言·c#
逑之1 天前
C语言笔记1:C语言常见概念
c语言·笔记·c#
福大大架构师每日一题1 天前
2026年1月TIOBE编程语言排行榜,Go语言排名第16,Rust语言排名13。C# 当选 2025 年度编程语言。
golang·rust·c#
wangnaisheng1 天前
【C#】gRPC的使用,以及与RESTful的区别和联系
c#
JosieBook1 天前
【开源】基于 C# 和 Halcon 机器视觉开发的车牌识别工具(附带源码)
开发语言·c#
龙潜月七1 天前
做一个背单词的脚本
数据库·windows·c#·aigc·程序那些事
寻星探路1 天前
【Python 全栈测开之路】Python 基础语法精讲(一):常量、变量与运算符
java·开发语言·c++·python·http·ai·c#
故事不长丨1 天前
深度解析C#文件系统I/O操作:File类与FileInfo类的核心用法与场景对比
c#·文件系统·file·fileinfo·i/o操作·i/o流