我正在寻找这个问题的解决方案,当使用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
谢谢@xerous,是的它确实也适用于StackPanel。 – 2013-09-09 14:21:13