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

相关推荐
钰fly4 小时前
C#类型转换 显隐转换
c#
kylezhao20198 小时前
C#通过HSLCommunication库操作PLC用法
开发语言·c#
叫我A先生11 小时前
【OpenGL小作坊】C# + OpenTK + OpenGL实现.tif点云转换成.obj模型
c#·opengl
code bean11 小时前
【Halcon】Halcon模板匹配技术深度解析:形状匹配 vs 局部可形变匹配
c#·halcon
kylezhao201915 小时前
C#手写串口助手
开发语言·c#
向宇it15 小时前
2025年技术总结 | 在Unity游戏开发路上的持续探索与沉淀
游戏·unity·c#·游戏引擎
Tan385117 小时前
如何在 OfficeAI 上配置 API Key(图文教程)
开发语言·人工智能·c#·api·教程·officeai
薛勇17 小时前
.net中如何选择async/await 和Task.Run?
c#·.net
剑之所向17 小时前
c# 中间表
开发语言·c#
Lv117700817 小时前
初识Visual Studio中的 WinForm
开发语言·ide·笔记·c#·visual studio