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

相关推荐
数据的世界0129 分钟前
C#4.0权威指南第10章:继承
c#
小熊熊知识库2 小时前
MinIO文件对象存储使用(C#)
c#
Lv11770083 小时前
Visual Studio中的二维数组和交错数组
ide·笔记·c#·visual studio
阿蒙Amon6 小时前
C#每日面试题-值传递和引用传递的区别
java·面试·c#
yj爆裂鼓手7 小时前
unity对象池
unity·c#
Traced back8 小时前
Windows窗体应用 + SQL Server 自动清理功能方案:按数量与按日期双模式
数据库·windows·c#·.net
Aevget8 小时前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(五)?
wpf
阿蒙Amon8 小时前
C#每日面试题-索引器和迭代器的区别
开发语言·windows·c#
yangSnowy8 小时前
Redis数据类型
数据库·redis·wpf
资深web全栈开发8 小时前
分布式锁的陷阱:Redlock 真的安全吗?
分布式·安全·wpf