如何在 DataGrid 列标题上设置 DataContext
在我的 Silverlight 3 用户控件中,我显示了一个基本的 DataGrid 控件。我需要以编程方式生成列,如下所示:
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>
我想将标题的数据上下文设置为“标题”对象(使用“数据模板中引用的“名称”和“数据”属性)。不幸的是,我无法按照其他地方的建议使用 StackPanel_Loaded 事件,因为该事件当用户启动列拖放操作时也会调用处理程序。
设置 DataGrid 列标题的 DataContext 的正确方法是什么?
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);
The style is defined as follows:
<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>
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.
What is the correct way of setting the DataContext of a DataGrid column header?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是在 XAML 中执行此操作的方法(这适用于 WPF;不确定是否适用于 SL)
Here's how you would do it in XAML (this works in WPF; not sure if it works in SL)
事实证明,我们可以使用 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):
根据马特的回答,我想出了在
DataGridCellsPanel
上绑定标头的解决方案,在 Snoop 中它似乎具有正确的数据上下文:并且这不是侵入性的,您仍然可以继承自定义样式标题(参见上面的示例)或事件基本列标题样式:
此解决方案的优点是纯粹的 XAML,并引用持有正确数据上下文的最近祖先,而不是尝试访问 UserControl 等顶级层次结构元素的数据上下文。
Based on Matt's answer, I came up with the solution of binding the header on the
DataGridCellsPanel
which in Snoop appeared to have the correct data context :And this is non intrusive in the way that you can still inherits from custom styled headers (see exemple above) or event the base column header style:
This solution has the advantage of being pure and clean XAML and to refer to the closest ancestor holding the correct datacontext rather than trying to reach datacontext of top hierarchy elements like UserControl.