Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - DataGridTextColumn Header DataTemplate

This may (hopefully) have a trivial or very simple answer.

Suppose I want customized headings for my DataGrid. I can use a DataTemplate as so:

<DataGridTextColumn Binding="{Binding Name}">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="Header Text" TextWrapping="Wrap"/>
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

However, if there are many columns it is less cumbersome to be able to use something like

<DataGridTextColumn Binding="{Binding Name}">
    HeaderTemplate="{StaticResource ColumnHeaderTemplate}"
</DataGridTextColumn>

where ColumnHeaderTemplate is my custom DataTemplate. My question is how do I pass the "Header Text" to the DataTemplate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it by binding TextBlock.Text and you can do it either for all column headers in a DataGrid by changing ContentTemplate of header to be your custom TextBlock and then just set Header to text you want to display. It will also apply to automatically generated columns

<DataGrid ...>
   <DataGrid.Resources>
      <Style TargetType="{x:Type DataGridColumnHeader}">
         <Setter Property="ContentTemplate">
            <Setter.Value>
               <DataTemplate>
                  <TextBlock Text="{Binding}" TextWrapping="Wrap"/>
               </DataTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </DataGrid.Resources>
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Name}" Header="Header Text">
   </DataGrid.Columns>
</DataGrid>       

or can also do it per column just change TextBlock.Text in you header template to use binding, as above

<TextBlock Text="{Binding}" TextWrapping="Wrap"/>

and then you column could look like this:

<DataGridTextColumn 
    Binding="{Binding Name}" 
    HeaderTemplate="{StaticResource ColumnHeaderTemplate}"
    Header="Header Text"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...