wpf DataGridTextColumn 标题 DataTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26692234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:40:21  来源:igfitidea点击:

DataGridTextColumn Header DataTemplate

wpfxaml

提问by James Hirschorn

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

这可能(希望)有一个微不足道或非常简单的答案。

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

假设我想要为我的DataGrid. 我可以这样使用DataTemplate

<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 ColumnHeaderTemplateis my custom DataTemplate. My question is how do I pass the "Header Text" to the DataTemplate?

ColumnHeaderTemplate我的习惯在哪里DataTemplate。我的问题是如何将“标题文本”传递给DataTemplate?

回答by dkozl

You can do it by binding TextBlock.Textand you can do it either for all column headers in a DataGridby changing ContentTemplateof header to be your custom TextBlockand then just set Headerto text you want to display. It will also apply to automatically generated columns

您可以通过绑定来完成TextBlock.Text,您可以DataGrid通过将ContentTemplate标题更改为您的自定义TextBlock然后设置Header为您想要显示的文本来为a 中的所有列标题执行此操作。它也适用于自动生成的列

<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.Textin you header template to use binding, as above

或者也可以按列执行,只需更改TextBlock.Text标题模板即可使用绑定,如上所述

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

and then you column could look like this:

然后您的列可能如下所示:

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