我正在尋找這個問題的解決方案,當使用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