Reputation: 3038
How to access the elements inside wpf datagrid column header template through code?
there is a solution,but i couldn't make it work.
http://social.msdn.microsoft.com/Forums/en/wpf/thread/3237cb62-3a6a-4663-9f1e-7894cb24c674
actually i don't know whats
Control.nameproperty
and
Header
in the answer above?
Upvotes: 2
Views: 2624
Reputation: 31
For people who are still having this problem.
You have this template:
<DataTemplate x:Key="DataGridColumnHeaderTemplate">
<StackPanel>
<DockPanel x:Name="DockPanelFilter"></DockPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}"></TextBlock>
<Image x:Name="ImageLock" Source="Resources/lock.png" Width="14" Height="14" Margin="2,0,0,0"></Image>
</StackPanel>
</StackPanel>
</DataTemplate>
and you want to access the ImageLock image. You could use:
Public Shared BooAfterItemsPresenter As Boolean = False
Public Shared ColumnName As String = String.Empty
Public Shared Function FindVisualChildByName(Of T As DependencyObject)(parent As DependencyObject, name As String, columnNameI As String) As T
Dim ColumnNameInput As String = columnNameI
For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(parent) - 1
Dim child = VisualTreeHelper.GetChild(parent, i)
Dim controlName As String = TryCast(child.GetValue(Control.NameProperty), String)
If TypeName(child) = "DataGridCellsPanel" Then
BooAfterItemsPresenter = True
End If
If BooAfterItemsPresenter = True AndAlso TypeName(child) = "DataGridColumnHeader" Then
Dim DGColHeader = CType(child, DataGridColumnHeader)
If DGColHeader.Content IsNot Nothing Then
ColumnName = DGColHeader.Content.ToString
Else
ColumnName = ""
End If
End If
If controlName = name AndAlso ColumnName = ColumnNameInput Then
Return TryCast(child, T)
Else
Dim result As T = FindVisualChildByName(Of T)(child, name, ColumnNameInput)
If result IsNot Nothing Then
Return result
End If
End If
Next
Return Nothing
End Function
and then when you use this function:
Public Sub hideImageLock ()
Dim ImageLock = FindVisualChildByName(Of Image)(dataGrid, "ImageLock", "NEU2")
ImageLock.Visibility = Windows.Visibility.Collapsed
End Sub
I hope that it helps some people!
Upvotes: 1
Reputation: 12295
Name property is the name you give to that Control.
in xaml you specify it by x:Name or simply by Name property of that control like below . This mean you are creating an object of TextBox class whose name is TextBox1.
<TextBox x:Name="TextBox1"/>
<TextBox Name="TextBox2"/>
in code behind it is the name of object
TextBox TextBox1 = new TextBox();
Similarly Header is property of DataGridColumn.
I hope this will help.
Upvotes: 0