我有一个数据网格,每个列标题中都有一个按钮。这是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>
某些列需要隐藏按钮,因为它们不应该是可排序的。我写了这个方法来找到按钮。我在那里放了额外的代码,所以我可以看到找到了什么按钮,它的标签值。
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
隐藏/显示按钮的方法:
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
现在,当首次加载网格时,我调用SetStaticColumn(“Ex”,True)并且该按钮不会出现在Ex列中(它有效)。调试如下所示:
GetSortButton btn.Name: ExcelFilterButton; btn.Tag: Ex
GetSortButton Tag 'Ex' found.
但是当重新加载网格以显示更新的数据时,Ex列中的按钮再次可见(它不起作用)。调试显示:
GetSortButton btn.Name: ; btn.Tag:
btn is nothing: True
因此,此时按钮看起来没有Tag值,因此找不到它。什么时候绑定发生?我尝试在DataGrid.Loaded事件处理程序中设置DataGrid.ItemsSource之后调用该方法,也在DataGrid.AutoGeneratingColumn事件处理程序中。重新加载后我可以让按钮消失的唯一方法是创建一个调用方法的按钮,然后在重新加载网格后单击该按钮。我在这一点上感到困惑。
任何建议表示赞赏。