WPF基础入门-Class4-WPF绑定

WPF基础入门

Class4: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" });
            //数据绑定到grid
            grid.ItemsSource = test;
        }
    }
    public class Color
    {
        public string Code { get; set;}

        public string Name { get; set; }
    }

2、编写xaml绑定

<Grid>
		
        <DataGrid x:Name="grid" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Code}" Header="Code">DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding Name}" Header="Name">DataGridTextColumn>
                <DataGridTextColumn Header="操作">DataGridTextColumn>
                <DataGridTemplateColumn Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Border Width="10" Height="10" Background="{Binding Code}">Border>
                                <TextBlock Margin="10,0" Text="{Binding Name}">TextBlock>
                            StackPanel>
                        DataTemplate>
                    DataGridTemplateColumn.CellTemplate>
                DataGridTemplateColumn>
                
            DataGrid.Columns>
        DataGrid>
    Grid>

3、效果显示:
WPF基础入门-Class4-WPF绑定_第1张图片

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