使用其中包含文本块的 HeaderTemplate 时,我正在寻找解决此问题的方法。就我而言,我通过附加属性解决了这个问题。您可以看到我只是从标题模板中获取文本,并将其设置到标题属性中。这样剪贴板复制模式 IncludeHeader 可以按预期工作。
/// <summary>
/// WPF Data grid does not know what is in a header template, so it can't copy it to the clipboard when using ClipboardCopyMode="IncludeHeader".
/// This attached property works with a header template that includes one TextBlock. Text content from the templates TextBlock is copied to the
/// column header for the clipboard to pick up.
/// </summary>
public static class TemplatedDataGridHeaderText
{
private static readonly Type OwnerType = typeof(TemplatedDataGridHeaderText);
public static readonly DependencyProperty UseTextFromTemplateProperty = DependencyProperty.RegisterAttached("UseTextFromTemplate", typeof(bool), OwnerType, new PropertyMetadata(false, OnHeaderTextChanged));
public static bool GetUseTextFromTemplate(DependencyObject obj)
{
return (bool)obj.GetValue(UseTextFromTemplateProperty);
}
public static void SetUseTextFromTemplate(DependencyObject obj, bool value)
{
obj.SetValue(UseTextFromTemplateProperty, value);
}
private static void OnHeaderTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textColumn = d as DataGridTextColumn;
if (textColumn == null) return;
if (textColumn.HeaderTemplate == null) return;
var headerTemplateTexblockText = textColumn.HeaderTemplate.LoadContent().GetValue(TextBlock.TextProperty).ToString();
textColumn.Header = headerTemplateTexblockText;
}
}
xaml 看起来像这样....
<DataGrid ItemsSource="{Binding }" AutoGenerateColumns="False" IsReadOnly="True" VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding FlowRate.UserValue, StringFormat=N3}" HeaderTemplate="{StaticResource FlowRate}"
attachedProperties:TemplatedDataGridHeaderText.UseTextFromTemplate="True"/>
<DataGridTextColumn Binding="{Binding Pressure.UserValue, StringFormat=N3}" HeaderTemplate="{StaticResource Pressure}"
attachedProperties:TemplatedDataGridHeaderText.UseTextFromTemplate="True"/>
</DataGrid.Columns>
更多信息可以在这里找到...... http://waldoscode.blogspot.com/2014/08/issue-using-wpf-datagrid-columnheader.html