如何在自动生成其值的同时向 DataGrid 添加按钮? (C#, WPF)
How to add a button to a DataGrid while at the same time autogenerating its values? (C#, WPF)
所以我有一个接受 DataTable 并像这样放入 DataGrid 的方法:
myDataGrid.DataContext = myDataTable;
myDataGrid.AutoGenerateColumns = true;
我试过像这样添加 ItemSource:
ObservableCollection<Button> buttons = new ObservableCollection<Button>();
buttons.Add(new Button() { Content = "Open" });
dg.ItemsSource = buttons;
但它只是把整个事情搞砸了,用 Button
属性 名称替换列,用 myButton
值替换行。
tl;dr: 有没有办法在不弄乱数据的情况下向每一行添加一个按钮?
您不能通过绑定按钮列表来将按钮或任何其他控件添加到数据网格的单元格。您应该使用 ItemsSource 来绑定您想要在行中显示的实际数据。
相反,您需要向数据网格列集合添加一个 DataGridTemplateColumn 实例。然后为该列指定一个模板,该模板指定要在该新列的每一行中显示的按钮。
所以我有一个接受 DataTable 并像这样放入 DataGrid 的方法:
myDataGrid.DataContext = myDataTable;
myDataGrid.AutoGenerateColumns = true;
我试过像这样添加 ItemSource:
ObservableCollection<Button> buttons = new ObservableCollection<Button>();
buttons.Add(new Button() { Content = "Open" });
dg.ItemsSource = buttons;
但它只是把整个事情搞砸了,用 Button
属性 名称替换列,用 myButton
值替换行。
tl;dr: 有没有办法在不弄乱数据的情况下向每一行添加一个按钮?
您不能通过绑定按钮列表来将按钮或任何其他控件添加到数据网格的单元格。您应该使用 ItemsSource 来绑定您想要在行中显示的实际数据。
相反,您需要向数据网格列集合添加一个 DataGridTemplateColumn 实例。然后为该列指定一个模板,该模板指定要在该新列的每一行中显示的按钮。