WPF - How to bind a DataGridTemplateColumn
Although you can't bind a template column, you can bind one of the controls held in that column. This is how I solved a similar problem:
<DataGridTemplateColumn Header="ColumnHeader"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <local:CustomisedUIElement Text="{Binding Path=PropertyToBindTo}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn>
If I've understood the initial example properly, this would mean changing the logic of the GroupByField_Click()
method to check whether the sending column was a template column and then looking at the elements it contained to obtain the Binding object.
For me, ClipboardContentBinding
of DataGridTemplateColumn
is a solution:
Private Function FindBoundProperty(ByVal col As DataGridColumn) As String Dim boundColumn As DataGridBoundColumn = TryCast(col, DataGridBoundColumn) Dim boundPropertyName As String = "" Dim binding As Binding If col.DependencyObjectType.Name = "DataGridTextColumn" Then binding = TryCast(boundColumn.Binding, Binding) boundPropertyName = binding.Path.Path End If If col.DependencyObjectType.Name = "DataGridTemplateColumn" Then binding = TryCast(col.ClipboardContentBinding, Binding) boundPropertyName = binding.Path.Path End If Return boundPropertyNameEnd Function
It's a tricky one. We achieved the binding by traversing to its grandparent UserControl (we had DataGrid inside a UserControl) and the UserControl was bound to a Presenter (Model in our case).In the code below, check the property SelectedItem of AutoCompleteBox placed inside the DataGridTemplateColumn.
<wpfToolkit:DataGridTemplateColumn Header="{x:Static resources:Store.ItemNameC}" Width="0.60*"> <wpfToolkit:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <extended:HOAutoCompleteBox IsTextCompletionEnabled ="True" x:Name="ItemAutoCompleteBox" Populating="ItemAutoCompleteBox_Populating" DefaultType="HealthObject.ObjectModel.pSearchStockItemResult,HealthObject.ObjectModel" Text="{Binding Path= ItemName, Mode=TwoWay}" <!--- **** HERE IS THE BINDING SAMPLE *****--> SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=Model.SelectedStockItem, Mode=TwoWay}"> </extended:HOAutoCompleteBox> </DataTemplate> </wpfToolkit:DataGridTemplateColumn.CellEditingTemplate></wpfToolkit:DataGridTemplateColumn>