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、效果:

相关推荐
新手unity自用笔记4 小时前
项目-坦克大战学习-子弹的移动与销毁
笔记·学习·c#
qinzechen4 小时前
分享几个做题网站------学习网------工具网;
java·c语言·c++·python·c#
yufei-coder8 小时前
C# Windows 窗体开发基础
vscode·microsoft·c#·visual studio
dangoxiba8 小时前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十三集:制作小骑士的接触地刺复活机制以及完善地图的可交互对象
游戏·unity·visualstudio·c#·游戏引擎
AitTech8 小时前
深入理解C#中的TimeSpan结构体:创建、访问、计算与格式化
开发语言·数据库·c#
hiyo58512 小时前
C#中虚函数和抽象函数的概念
开发语言·c#
芝麻科技14 小时前
使用ValueConverters扩展实现枚举控制页面的显示
wpf·prism
开心工作室_kaic14 小时前
基于微信小程序的校园失物招领系统的设计与实现(论文+源码)_kaic
c语言·javascript·数据库·vue.js·c#·旅游·actionscript
时光追逐者19 小时前
WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!
前端·microsoft·开源·c#·.net·layui·.netcore
friklogff20 小时前
【C#生态园】打造现代化跨平台应用:深度解析.NET桌面应用工具
开发语言·c#·.net