tags:

views:

175

answers:

2

I have a datagrid in which I am using DataGridTemplateColumn and DataGridTextColumn. I want to access these columns at runtime so I have assigned x:Name property to them. But I was not getting that value in code behind, so I looked for DataGrid and then read objects by iterating through DataGrid.Columns. How can I read x:Name property from that object in C#?

I need this to perform some specific operations with particular columns at runtime.

A: 

the datagrid column does not get added to the visual tree. (so maybe you cant access it in the code behind because of this) - see vinces blog on the visual layout.

you can look at the header property, or you could derive and add your own property to uniquely identify the column. thats what i do, ive found the columns a bit vanilla and have derived a fair few for different uses.

Aran Mulholland
A: 

Another alternative is to define an attached property:

1) Derive a new class from DataGrid with the attached property Public Class FilteringDataGrid Inherits DataGrid

Public Shared Function GetFilterProp(ByVal element As DependencyObject) As String If element Is Nothing Then Throw New ArgumentNullException("element") End If

  Return CStr(element.GetValue(FilterPropProperty))

End Function

Public Shared Sub SetFilterProp(ByVal element As DependencyObject, ByVal value As String) If element Is Nothing Then Throw New ArgumentNullException("element") End If

  element.SetValue(FilterPropProperty, value)

End Sub

Public Shared ReadOnly FilterPropProperty As _ DependencyProperty = DependencyProperty.RegisterAttached("FilterProp", _ GetType(String), GetType(FilteringDataGrid), _ New FrameworkPropertyMetadata(Nothing)) End Class

2) Set the prop in Xaml

3) Read the value

klawusel