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

相关推荐
月巴月巴白勺合鸟月半1 小时前
PDF转图片的另外一种方法
pdf·c#
m5655bj1 小时前
使用 C# 对比两个 PDF 文档的差异
pdf·c#·visual studio
Never_Satisfied1 小时前
C#插值字符串中大括号表示方法
前端·c#
wy3136228213 小时前
C#——意框架(结构说明)
前端·javascript·c#
kylezhao20193 小时前
C# 各种类型转换深入剖析
开发语言·c#
xb11324 小时前
Winform控件样式
c#
作孽就得先起床4 小时前
unity webGL导出.glb模型
unity·c#·游戏引擎·webgl
Java程序员威哥4 小时前
Java应用容器化最佳实践:Docker镜像构建+K8s滚动更新(生产级完整模板+避坑指南)
java·开发语言·后端·python·docker·kubernetes·c#
垂葛酒肝汤4 小时前
C#的const和static的问题
开发语言·c#
xb11325 小时前
WinForms 多窗体应用程序详解
数据库·microsoft·c#