WPF基础入门-Class3-WPF数据模板

WPF基础入门

Class3:WPF数据模板

1、先在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中编写模板

<Grid>
        
        <ListBox x:Name="list">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        
                        <Border
                            Width="10"
                            Height="10"
                            Background="{Binding Code}">Border>
                        <TextBlock Margin="10, 0" Text="{Binding Name}">TextBlock>
                    StackPanel>
                DataTemplate>
            ListBox.ItemTemplate>
        ListBox>
Grid>

3、效果:
WPF基础入门-Class3-WPF数据模板_第1张图片

你可能感兴趣的:(WPF基础入门,wpf,c#)