上善若水

水善利万物而不争
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

WPF | 跟着视频敲代码5 | 数据模板

Posted on 2022-07-19 06:29  董锡振  阅读(22)  评论(0编辑  收藏  举报

视频地址:https://www.bilibili.com/video/BV1nY411a7T8?p=4

 

<DataGrid  x:Name="DataGrid1" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Code"  Binding="{Binding Code}"></DataGridTextColumn>
                <DataGridTextColumn Header="Name"  Binding="{Binding Name}"></DataGridTextColumn> 
                <DataGridTemplateColumn Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button   Margin="5,0"  Content="删除"></Button>
                                <Button   Margin="5,0"  Content="复制"></Button>
                                <Border   Margin="5,0"  Height="10" Width="10"  Background="{Binding Code}"></Border>
                                <TextBlock Text="{Binding Name}"></TextBlock> 
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid> 
/// <summary>
    /// Demo5.xaml 的交互逻辑
    /// </summary>
    public partial class Demo5 : Window
    {
        public Demo5()
        {
            InitializeComponent();
            //for (var i = 0; i < 10; i++)
            //{
            //    list1.Items.Add(new ListBoxItem()
            //    {
            //        Content = new TextBlock()
            //        {
            //            Text = i.ToString()
            //        }
            //    });
            //}

            List<Color> test = new List<Color>();
            test.Add(new Color() { Code = "#FFB6C1", Name = "粉红色" });
            test.Add(new Color() { Code = "#FF0000", Name = "红色" });
            //list.ItemsSource = test; 
            DataGrid1.ItemsSource = test; 
        }
    }

    public class Color
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }