I have a datagrid with a button in each column header. Here's the XAML:
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button x:Name="ExcelFilterButton"
Margin="0,0,0,0"
BorderThickness="0"
Click="ExcelFilterButton_Click"
Focusable="False"
Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
Tag="{Binding}">
<Image Width="19"
Height="19"
Source="Resources\NoSortNoFilter.png"
Tag="{Binding}" />
</Button>
<TextBlock x:Name="ColumnName"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
There are certain columns that need to hide the button because they should not be sortable. I wrote this method to find the button. I put extra code in there so I could see what button was found and it's tag value.
Private Sub GetSortButton(Of T As DependencyObject)(dep As DependencyObject, Tag As String, ByRef out As T)
If dep IsNot Nothing Then
If TypeOf dep Is Button Then
Dim btn As Button = CType(dep, Button)
Debug.WriteLine("GetSortButton btn.Name: " & btn.Name & "; btn.Tag: " & btn.Tag)
If btn.Tag = Tag Then out = dep
Else
If VisualTreeHelper.GetChildrenCount(dep) > 0 Then
For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(dep) - 1
GetSortButton(Of T)(VisualTreeHelper.GetChild(dep, i), Tag, out)
Next
End If
End If
End If
End Sub
And a method to hide/show the button:
Public Sub SetStaticColumn(ColumnName As String, IsStatic As Boolean)
Dim btn As Button = Nothing
GetSortButton(Of Button)(dataGrid, ColumnName, btn)
Debug.WriteLine("btn is nothing: " & (btn Is Nothing).ToString)
If btn IsNot Nothing Then
btn.Visibility = If(IsStatic, Visibility.Collapsed, Visibility.Visible)
End If
End Sub
Now, when the grid is first loaded, I call the SetStaticColumn("Ex", True) and the button doesn't appear in the Ex column (it worked). The debug looks like this:
GetSortButton btn.Name: ExcelFilterButton; btn.Tag: Ex
GetSortButton Tag 'Ex' found.
But when the grid is reloaded to display updated data, the button in the Ex column is again visible (it didn't work). And the debug shows:
GetSortButton btn.Name: ; btn.Tag:
btn is nothing: True
So it looks like the button didn't have a Tag value at this point so it wasn't found. When does the binding happen? I've tried calling the method after setting the DataGrid.ItemsSource, also in the DataGrid.Loaded event handler, also in the DataGrid.AutoGeneratingColumn event handler. The only way I can get the button to disappear after a reload is to create a button that calls the method and then click that button after the grid is reloaded. I'm baffled at this point.
Any suggestions appreciated.