I have a DataGrid
in WPF. And I am trying to add Button
s to certain cells of the grid, after it is bound to a particular ItemsSource
. I have tried to do this in the xaml like this:
<dg:DataGridTemplateColumn x:Name="R1" CanUserReorder="False" IsReadOnly="False">
<dg:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<awc:ImageButton Content="Edit" Name="btnEdit" Visibility="Collapsed"/>
</DataTemplate>
</dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
However, I want to know as to how I can do this in the code behind. I need this so that I can place Button
s whenever a particular click even takes place. Any help will be highly appreciated.
Anurag's answer will work very well for you if you want to add the buttons before the grid is instantiated, specifically before you add the column to the grid.
If you want to add the button to the grid cell after the grid is already built, you can do it by making changes to the DataGridCell object. First you have to find it:
DataGridCell
by usingDataGridColumn.GetCellContent
VisualTreeHelper
to scan up the visual tree to theDataGridCell
Once this is done, there are several ways to add a button to the DataGridCell, depending on what you're trying to achieve:
DataGridCell.Template
to a ControlTemplate containing the buttons and other styling you desire, -OR-DataGridCell.ContentTemplate
to a DataTemplate containing the buttons and other items you desire, -OR-DataTemplate
include a placeholder panel to hold new buttons, search down the visual tree for this panel byName
, and add your button to it.An alternative approach that doesn't require finding the cell is to:
ObservableCollection<T>
property in your view model that supplies the information to create the buttonsDataTemplate
include anItemsControl
that reference this property and has aDataTemplate
that can create the correct button out of typeT
ObservableCollection
propertyuse this:
I used this to add CheckBox in my DataGridTemplateColumn at runtime. Hope this helps!!