由于某种原因,DataGrid 的列标题不是 FrameWork 元素,因此您不能使用绑定(bind)来设置标题文本之类的内容。如果 .NET 4.0 改变了这种情况,请纠正我(我现在使用的是 CodePlex 的最新 WPFToolkit)。
我正在尝试将 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 属性绑定(bind)到标题文本。有人可以告诉我该怎么做吗?如果我有要使用静态资源,我怎样才能在其中获取 DataContext?
编辑 ---------------- 首选解决方法
Josh Smith 曾发布过关于 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();
}
}
有了这个,我可以在 xaml 中劫持我需要的 DC:
<dg:DataGrid.Resources>
<behavior:DataContextSpy x:Key="spy" DataContext="{Binding Allocations}" />
</dg:DataGrid.Resources>
然后根据需要通过绑定(bind)应用:
<dg:DataGridTextColumn Header="{Binding Source={StaticResource spy}, Path=DataContext[0].DisplayName}"
Width="50" Binding="{Binding Allocations[0].Amount}" />
苏湿!
最佳答案
我知道这篇文章很旧,但是当我查找如何执行此操作时,这是出现的第一个条目。我不喜欢这个答案,因为它看起来有点矫枉过正。经过更多搜索,我遇到了这个link展示了如何使用模板列在标记中执行此操作。
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
**<TextBlock Text="{Binding DataContext.HeaderTitle, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />**
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Width="200" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
关于WPF 数据网格标题文本绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1658397/