我正在尝试编写一些代码,以允许通过 TextBox 或 ComboBox 过滤 DataGrid。我已经为 TextBox 设置了过滤代码,现在对于 Combobox 类型的过滤器,我不太确定这种方法。
首先,我继承了 DataGrid,我所有的过滤代码都放在那里。为了将过滤器放在数据网格上,我选择了 DataGrid 的标题。我不想使用继承的 DataGrid 类中定义的附加属性来控制要显示的过滤器类型。这是其中一个标识要使用的过滤器类型(文本框或组合框)。
public class FilteringDataGrid : DataGrid {
....
//Dependency Properties for Combobox or Text search.
public static DependencyProperty FilterTypeProperty = DependencyProperty.RegisterAttached("FilterType",
typeof(FilterTypeEnum), typeof(DataGrid), new PropertyMetadata(FilterTypeEnum.TextBoxOnly));
它设置在 DataGridColumn 级别。
在 DataGrid ColumnHeaderTemplate 中,我试图阅读上面的附加属性。但是我不知道如何在 ColumnHeaderTemplate 中访问在列级别设置的属性。我将在 Trigger 中使用此属性值将 TextBox 或 Combobox 呈现为过滤器。如何在 ColumnHeaderTemplate(或准确地说是模板触发器)中访问此属性的值。
这是 DataGrid ColumnHeaderTemplate 的相关部分
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:fg="clr-namespace:ThemingControls.CustomControls"> <!--Inherited DataGrid Control namespace -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0" Grid.Row="0"
....
<Path x:Name="SortArrow"
Grid.Column="1" Grid.Row="0"
....
<!-- Combobox or TextBox show either one based on Column FilterType attached Property -->
<ComboBox Grid.Row="1" Grid.ColumnSpan="2" IsEditable="False"
/>
<fg:DelayTextBox Grid.Row="1" Grid.ColumnSpan="2" />
....
<!-- Triggers to show TextBox/Combobox based on attached property of column -->
<ControlTemplate.Triggers>
<Trigger Property="fg:FilteringDataGrid.FilterType" Value="NonEditableComboBox">
<Setter Property="fg:DelayTextBox.Visibility" Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
上面的代码运行,但我在所有列中都得到了 Combobox 类型的过滤器,即使某些列将 TextBox 设置为附加属性(FilterType)。这意味着上面的触发器不起作用。任何想法如何访问 datagrid 列中的附加属性集。IE。在 ColumnHeaderTemplate 中访问它更准确。