WPF DataGrid 绑定数据并通过CellTemplae提供编辑删除按钮

前端代码

 <Grid>
        <DataGrid Name="gd" CanUserSortColumns="True" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding UserName}" Width="100" Header="学生姓名"/>
                <DataGridTextColumn Binding="{Binding ClassName}" Width="100" Header="班级"/>
                <DataGridTextColumn Binding="{Binding Address}" Width="100" Header="地址"/>
                <DataGridTemplateColumn  Header="操作" Width="100">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Left">
                                <Button Content="编辑" Margin="10 0 10 0" Height="22" Width="30"/>
                                <Button Content="删除" Height="22" Width="30"/>
                            </StackPanel>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
AutoGenerateColumns="False" 获取或设置一个值,该值指示是否为数据源中的每个字段自动创建绑定字段。GridView.AutoGenerateColumns 属性 (System.Web.UI.WebControls) | Microsoft Docs

CanUserAddRows="False" Gets or sets a value that indicates whether the user can add new rows to the DataGrid. DataGrid.CanUserAddRows Property (System.Windows.Controls) | Microsoft Docs
DataGridTemplateColumn 设置 CellTemplate,然后设置datatemplate 提供模板样式设置


后台代码
  var students = new List<Student>();
            students.Add(new Student { UserName = "小明", ClassName = "一班", Address = "故宫" });
            students.Add(new Student { UserName = "小红", ClassName = "二班", Address = "三元桥" });
            students.Add(new Student { UserName = "张三", ClassName = "三班", Address = "十里河" });
            students.Add(new Student { UserName = "李四", ClassName = "四班", Address = "西二旗" });
            this.gd.ItemsSource = students;
 public class Student
    {
        public string UserName { get; set; }
        public string ClassName { get; set; }
        public string Address { get; set; }
    }

 源码地址:https://gitee.com/houzhifei/wpf-demo.git

posted @ 2021-11-11 10:56  吃葡萄不吐葡萄脾  阅读(526)  评论(0编辑  收藏  举报