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

相关推荐
-银雾鸢尾-21 小时前
C#中的反射关键类-Type
开发语言·c#
淡海水1 天前
15-07-YooAsset面试篇-Unity性能优化与内存管理
java·unity·面试·性能优化·c#·游戏引擎
dalong101 天前
WPF:3D型材模型
3d·wpf
hez20101 天前
.NET 11 Runtime Async 详解
c#·.net·.net core
猿长大人2 天前
C# | Serilog 新手入门
开发语言·c#·.net·log
在世修行2 天前
从零打造 C# 工业视觉检测系统(七):串口通信 SerialPort 封装与开发
开发语言·c#·modbus rtu·rs232/rs485
NoteStream2 天前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
lzhdim2 天前
C# 通过 Windows API 实现进程内存读写操作
开发语言·windows·c#
-银雾鸢尾-2 天前
C#中的预处理指令
开发语言·c#
dalong102 天前
Savitzky-Golay 的C# 实现
开发语言·kotlin·c#