首页 > 解决方案 > 用于 DataGrid 标头的 wpf 可重用模板

问题描述

在这里,我设计了一个 DataTemplate 用于 DataGrid 的标题中,以便为过滤提供 UI。
它只是一个添加到标头标准内容中的按钮。
该按钮有一个指向模板的宿主类的命令。
最简单的起点。

    <DataTemplate x:Key="myFilterHeader">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{TemplateBinding Content}"/>
            <Button Margin="5,0,0,0" 
                    Command="{Binding FilterCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
                    CommandParameter="{TemplateBinding Content}">
                <Path Fill="DarkBlue" Width="11px" Stretch="Uniform" >
                    <Path.Data>
                        <PathGeometry Figures="m 242.678 412.212 h -73.143 c -15.05738 0 -15.673 -0.30785 -15.673 -15.673 V 256.45921 L 10.71 24.555 C 7.053 19.853 -0.42883798 0.02223789 -0.42883798 0.02223789 -0.42883798 0.02223789 16.98 0 23.249 0 h 365.714 c 5.747 0 23.67784 0.33100686 23.67784 0.33100686 0 0 -7.48184 19.52199314 -11.13884 24.22399314 L 258.351 256.45921 V 396.539 c 0 14.43884 1.85353 15.673 -15.673 15.673 z m -57.47 -31.347 h 41.796 V 251.23521 c 0 -3.135 1.045 -6.792 3.135 -9.404 L 358.139 30.825 H 54.073 l 128 211.00621 c 2.09 2.612 3.135 5.747 3.135 9.404 z" FillRule="NonZero"/>
                    </Path.Data>
                </Path>
            </Button>
        </StackPanel>
    </DataTemplate>

带有模板列标题的数据网格

我的意图是在应用程序周围的多个 Datagrid 中重用它。
阻止我这样做的是命令模式;考虑这一行:

            <Button Margin="5,0,0,0" 
                    Command="{Binding FilterCommand, 
                              RelativeSource={RelativeSource FindAncestor, 
                              AncestorType={x:Type Window}}}" 
                    CommandParameter="{TemplateBinding Content}">

它之所以有效,是因为我的 datacontext 类具有以下属性:

public ICommand FilterCommand { get; } = new SimpleFilterCommand();

这反过来又指向我的Fitering实现。

如果我在同一个窗口中有多个 DataGrid,我想使用相同的模板“myFilterHeader”指向不同的 FilterCommand 属性,比如说每个网格一个。
我怎样才能做到这一点?如果不可行,如何以对 wpf 更友好的方式实现这一目标?考虑到这个模板是故意简单的,只是为了适合一个样本。在实际应用中它会更复杂,这就是我寻找可重用性策略的原因。

标签: c#wpf

解决方案


推荐阅读