使用 WPF 中的样式样式 DataGridColumnHeader [英] Style DataGridColumnHeader with Styles in WPF

查看:92
本文介绍了使用 WPF 中的样式样式 DataGridColumnHeader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一种在 DataGrid 中过滤我的记录的方法.我的想法是将 TextBoxes 放在每列的 Header 中.

Hi i am trying to implement a way to filter my records in a DataGrid. My idea is to put TextBoxes in the Header of each Column.

我这样做取决于是否按下了 ToggleButton,但我在应用标题中的样式时遇到了问题.

I am doing this depending if a ToggleButton is pressed or not, but i am having a problem in the way that i am applying the style in the Header.

如果我像这样在 DataGridColumn 中应用样式:

If i apply the style inside the DataGridColumn like this:

<DataGridTextColumn>
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            (...)
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

它会完美运行!

但是如果尝试把它放在一个 Style 中,我会这样做:

But if try to put this in a Style i am doing it like this:

<Style TargetType="{x:Type DataGridTextColumn}">
    <Setter Property="Template">
        <ControlTemplate>
            (...)
        </ControlTemplate>
    </Setter>
</Style>

通过使用 ControlTemplate,我们将覆盖背景和 DataGridColumnHeader 的所有默认布局,我不想要那样.我该怎么做?

By using the ControlTemplate we will override the background and all the Default layout of DataGridColumnHeader and i don't want that. How i can i do this?

我真的很想这样做以避免在 XAML 中重复代码.

I am really tring to do this to avoid repeat code in XAML.

提前致谢!

推荐答案

如果您使用 DataTemplate 方法的唯一原因是因为您想定义它一次(在某个中心位置)并且然后在多个地方(例如多个列)使用它,您可以将该 DataTemplate 移动到资源部分,为其分配一个资源键并在任何您想要的地方使用它.

方法如下:

If the only reason you are not using the DataTemplate approach is because you want to define it once (at some central location) and then use it at multiple places (e.g. multiple columns), you can move that DataTemplate to the resources section, assign it a resource key and use it whereever you want.

Here's how:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300" Loaded="Window_Loaded">
    <Window.Resources>
        <DataTemplate x:Key="MySpecialHeaderTemplate">
            <TextBox Text="Search..." />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn
                        Binding="{Binding Id}" />
                <DataGridTextColumn HeaderTemplate="{StaticResource MySpecialHeaderTemplate}"
                        Binding="{Binding Name}" />
                <DataGridTextColumn HeaderTemplate="{StaticResource MySpecialHeaderTemplate}"
                        Binding="{Binding Age}" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

这篇关于使用 WPF 中的样式样式 DataGridColumnHeader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆