如何在 DataGrid 列标题上设置 DataContext [英] How to set the DataContext on a DataGrid Column Header
问题描述
在我的 Silverlight 3 用户控件中,我展示了一个基本的 DataGrid 控件.我需要以编程方式生成列,如下所示:
In my Silverlight 3 user control I am showing a basic DataGrid control. I need to generate the columns programmatically as follows:
Style headerStyle = (Style)Resources["ColumnHeaderStyle"];
DataGridTextColumn col = new DataGridTextColumn();
col.HeaderStyle = headerStyle;
dataGrid.Columns.Add(col);
样式定义如下:
<Style x:Name="ColumnStyle" x:Key="ColumnHeaderStyle"
TargetType="prim:DataGridColumnHeader">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Loaded="StackPanel_Loaded">
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Data}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
我想将标头的数据上下文设置为标头"对象(具有在 DataTemplate 中引用的名称"和数据"属性).不幸的是,我不能按照其他地方的建议使用 StackPanel_Loaded 事件,因为该事件处理程序也会在用户开始列拖放操作时调用.
I want to set the data context of the header to a "header" object (with "Name" and "Data" properties which are referenced in the DataTemplate). Unfortunately, I cannot use the StackPanel_Loaded event as suggested elsewhere, because the event handler is also called when the user starts a column drag&drop operation.
设置 DataGrid 列标题的 DataContext 的正确方法是什么?
What is the correct way of setting the DataContext of a DataGrid column header?
推荐答案
原来可以使用 Header 属性(属于 Object 类型)作为 DataTemplate 的 DataContext(如上图设置):
Turns out that one can use the Header property (which is of type Object) as the DataContext for the DataTemplate (set as shown above):
Style headerStyle = (Style)Resources["ColumnHeaderStyle"];
DataGridTextColumn col = new DataGridTextColumn();
col.HeaderStyle = headerStyle;
col.Header = myHeaderDataContext; // DataContext for ColumnHeaderStyle
dataGrid.Columns.Add(col);
这篇关于如何在 DataGrid 列标题上设置 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!