如何在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>
我想将标题的数据上下文设置为header对象(具有DataTemplate中引用的Name和Data属性)。不幸的是,我不能像建议的其他地方使用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?
推荐答案
结果可以使用头文件属性(其类型为Object)作为 DataContext DataTemplate (设置如上所示):
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屋!