在 Silverlight DataGrid 中,我想在用户右键单击其中一个列标题或列标题行中的其他位置时显示上下文菜单。我该怎么做呢?
问问题
385 次
1 回答
1
这是一个将为您执行此操作的行为:
public class ColumnHeaderContextMenu : Behavior<DataGrid>
{
public static readonly DependencyProperty ContextMenuProperty =
DependencyProperty.Register("ContextMenu", typeof (ContextMenu), typeof (ColumnHeaderContextMenu), new PropertyMetadata(default(ContextMenu)));
public ContextMenu ContextMenu
{
get { return (ContextMenu) GetValue(ContextMenuProperty); }
set { SetValue(ContextMenuProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += HandleLoaded;
AssociatedObject.Unloaded += HandleUnloaded;
}
private void HandleUnloaded(object sender, RoutedEventArgs e)
{
if (ContextMenu != null)
{
ContextMenu.Owner = null;
}
}
private void HandleLoaded(object sender, RoutedEventArgs e)
{
var columnHeadersPresenter = AssociatedObject.GetVisualDescendants().OfType<DataGridColumnHeadersPresenter>().FirstOrDefault();
if (ContextMenu != null)
{
ContextMenu.Owner = columnHeadersPresenter;
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= HandleLoaded;
AssociatedObject.Unloaded -= HandleUnloaded;
}
}
像这样使用它:
<sdk:DataGrid>
<i:Interaction.Behaviors>
<Behaviors:ColumnHeaderContextMenu>
<Behaviors:ColumnHeaderContextMenu.ContextMenu>
<Controls:ContextMenu>
<Controls:MenuItem Header="Choose Columns" Command="{Binding EditColumns}"/>
</Controls:ContextMenu>
</Behaviors:ColumnHeaderContextMenu.ContextMenu>
</Behaviors:ColumnHeaderContextMenu>
</i:Interaction.Behaviors>
</sdk:DataGrid>
于 2012-05-10T09:40:12.453 回答