Style DataGridColumnHeader with Styles in WPF

不问归期 提交于 2019-12-11 15:24:56

问题


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.

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.

If i apply the style inside the DataGridColumn like this:

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

It will work perfectly!

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>

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?

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

Thanks in advance!


回答1:


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>


来源:https://stackoverflow.com/questions/5760545/style-datagridcolumnheader-with-styles-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!