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 小时前
c# 集成激光雷达(以思岚A1为例)
开发语言·c#
无极小卒21 小时前
如何在三维空间中生成任意方向的矩形内部点位坐标
开发语言·算法·c#
the白勺1 天前
RabbitMQ-基础-总结
开发语言·c#
专注VB编程开发20年1 天前
C#VB.NET中实现可靠的文件监控(新建、删除、改名、内容修改等事件的准确捕获)
spring·c#·.net·文件监控
yi碗汤园1 天前
【一文了解】C#反射
开发语言·unity·c#
T.Ree.1 天前
汇编_读写内存
开发语言·汇编·c#
czhc11400756631 天前
C#1114 枚举
开发语言·c#
曹牧1 天前
C#中,GetValueOrDefault方法
c#
SunnyDays10111 天前
使用 C# 实现 Excel 与 DataTable 相互转换
c#·excel转datatable·datatable转excel
獨枭2 天前
C# 本地项目引用失效与恢复全攻略
开发语言·c#·visual studio