在动态生成的DataGrid中添加操作列

时间:2018-08-31 10:14:43

标签: c# wpf

我正在使用此代码动态生成DataGrid控件:

//c# code
DataGrid dg = new DataGrid();
dg.HorizontalAlignment = HorizontalAlignment.Center;
dg.VerticalAlignment = VerticalAlignment.Top;
dg.AutoGenerateColumns = true;
getData gd = new getData();
UserData[] userData = gd.getUserRecord();
dg.ItemsSource = userData;

panel1.Children.Add(dg);

//XAML code
<StackPanel Name="panel1"  ScrollViewer.VerticalScrollBarVisibility="Visible" Margin="18.971,24,24,0" Grid.Column="1">

现在,我想向此数据网格添加一个名为“ Action”的附加列,并且在每一行上,它都应具有一个删除和编辑按钮。我通过互联网进行搜索,但只得到了仅动态生成操作列的结果,而我需要所有控件才能动态生成。

PS:UserData是我的自定义getter / setter类,getData具有从数据库获取数据的方法。

1 个答案:

答案 0 :(得分:1)

您可以使用DataGridTemplateColumn创建一个CellTemplate

DataGrid dg = new DataGrid();
dg.HorizontalAlignment = HorizontalAlignment.Center;
dg.VerticalAlignment = VerticalAlignment.Top;
dg.AutoGenerateColumns = true;
getData gd = new getData();
UserData[] userData = gd.getUserRecord();
dg.ItemsSource = userData;

FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel));
sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
FrameworkElementFactory delete = new FrameworkElementFactory(typeof(Button));
delete.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) => { MessageBox.Show("deleted click!"); }));
delete.SetValue(ContentControl.ContentProperty, "Delete");
FrameworkElementFactory edit = new FrameworkElementFactory(typeof(System.Windows.Controls.Button));
edit.AddHandler(Button.ClickEvent, new RoutedEventHandler((s, e) => { MessageBox.Show("edited click!"); }));
edit.SetValue(ContentControl.ContentProperty, "Edit");
edit.SetValue(FrameworkElement.MarginProperty, new Thickness(5, 0, 0, 0));
sp.AppendChild(delete);
sp.AppendChild(edit);

DataGridTemplateColumn dataGridTemplateColumn = new DataGridTemplateColumn()
{
    Header = "new...",
    CellTemplate = new DataTemplate { VisualTree = sp }
};

dg.Columns.Add(dataGridTemplateColumn);