Заголовок столбца DataGrid по какой-то причине не является элементом FrameWork, поэтому вы не можете использовать привязки для установки таких вещей, как текст заголовка. Пожалуйста, исправьте меня, если это неверно, если это изменилось с .NET 4.0 (теперь я использую последний WPFToolkit из CodePlex).
Я пытаюсь использовать DataGrid для представления временного листа, где дата дня должна быть частью текста заголовка (например, "Sun, Nov 01" ), и у меня есть следующее в моем XAML:
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Header="Description" Width="Auto" Binding="{Binding Description}" IsReadOnly="True"/>
<dg:DataGridTextColumn Header="Mon" Width="50" Binding="{Binding Allocations[0].Amount}" />
... every other day of the week ....
<dg:DataGridTextColumn Header="Sun" Width="50" Binding="{Binding Allocations[6].Amount}" />
<dg:DataGridTextColumn Header="Total" MinWidth="50" Binding="{Binding TotalAllocatedAmount}" IsReadOnly="True" />
</dg:DataGrid.Columns>
Я хотел бы использовать тот же AllocationViewModel, который я использую для данных (т.е. "{Binding Allocations [0].Amount}" и привязать его свойство DisplayName к тексту заголовка. Может ли кто-нибудь показать мне, как это сделать? Если мне нужно использовать статический ресурс, как я могу получить DataContext там?
РЕДАКТИРОВАТЬ ---------------- ПРЕДПОЧТИТЕЛЬНАЯ РАБОТА-ВОКРУГ
Джош Смит некоторое время писал о DataContextSpy, и это самый простой обходной путь, с которым я столкнулся с этой проблемой. Вот класс, который заставляет его работать:
/// <summary>
/// Workaround to enable <see cref="DataContext"/> bindings in situations where the DataContext is not redily available.
/// </summary>
/// <remarks>http://blogs.infragistics.com/blogs/josh_smith/archive/2008/06/26/data-binding-the-isvisible-property-of-contextualtabgroup.aspx</remarks>
public class DataContextSpy : Freezable
{
public DataContextSpy()
{
// This binding allows the spy to inherit a DataContext.
BindingOperations.SetBinding(this, DataContextProperty, new Binding());
}
public object DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
// Borrow the DataContext dependency property from FrameworkElement.
public static readonly DependencyProperty DataContextProperty = FrameworkElement
.DataContextProperty.AddOwner(typeof (DataContextSpy));
protected override Freezable CreateInstanceCore()
{
// We are required to override this abstract method.
throw new NotImplementedException();
}
}
С этим на месте я могу захватить DC, который мне нужен, в xaml:
<dg:DataGrid.Resources>
<behavior:DataContextSpy x:Key="spy" DataContext="{Binding Allocations}" />
</dg:DataGrid.Resources>
И затем примените по мере необходимости через привязку:
<dg:DataGridTextColumn Header="{Binding Source={StaticResource spy}, Path=DataContext[0].DisplayName}"
Width="50" Binding="{Binding Allocations[0].Amount}" />
Suh-Weet!