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

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


慕尼黑的夜晚无繁华
浏览 327回答 1
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(){&nbsp; &nbsp; Header = "new...",&nbsp; &nbsp; CellTemplate = new DataTemplate { VisualTree = sp }};dg.Columns.Add(dataGridTemplateColumn);
打开App,查看更多内容
随时随地看视频慕课网APP