我使用以下代码动态生成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
有从数据库中获取数据的方法。
你可以用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);