【发布时间】:2010-06-15 12:49:35
【问题描述】:
有没有办法让右键单击事件在工具包数据网格中选择一行?
我正在使用运行良好的工具包上下文菜单,但问题是,只有左键单击才能选择行,如果我希望上下文菜单正常工作,我需要右键单击才能执行此操作。
感谢任何帮助
【问题讨论】:
标签: c# silverlight datagrid contextmenu
有没有办法让右键单击事件在工具包数据网格中选择一行?
我正在使用运行良好的工具包上下文菜单,但问题是,只有左键单击才能选择行,如果我希望上下文菜单正常工作,我需要右键单击才能执行此操作。
感谢任何帮助
【问题讨论】:
标签: c# silverlight datagrid contextmenu
您可以找到解决方案here。
基本上是这样的:
private void dg_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.MouseRightButtonDown += new MouseButtonEventHandler(Row_MouseRightButtonDown);
}
void Row_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
dg.SelectedItem = ((sender) as DataGridRow).DataContext;
}
【讨论】:
他是一种可以为您解决问题的行为(受此 blog post 启发):
public class SelectRowOnRightClickBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.MouseRightButtonDown += HandleRightButtonClick;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseRightButtonDown += HandleRightButtonClick;
}
private void HandleRightButtonClick(object sender, MouseButtonEventArgs e)
{
var elementsUnderMouse = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), AssociatedObject);
var row = elementsUnderMouse
.OfType<DataGridRow>()
.FirstOrDefault();
if (row != null)
AssociatedObject.SelectedItem = row.DataContext;
}
}
像这样使用它:
<sdk:DataGrid x:Name="DataGrid" Grid.Row="4"
IsReadOnly="True"
ItemsSource="{Binding MyItems}">
<i:Interaction.Behaviors>
<b:SelectRowOnRightClickBehavior/>
</i:Interaction.Behaviors>
</sdk:DataGrid>
【讨论】:
谢谢好主意。但是已经指定了 with UnloadingRow 事件可能更有效。
private void dg_UnloadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
{
e.Row.MouseRightButtonDown -= Row_MouseRightButtonDown;
}
【讨论】:
Codeplex 上的这个开源项目开箱即用地支持这种行为,并且做的远不止这些:
【讨论】:
我使用 DataGrid 中的 LoadingRow 事件尝试了一种稍微不同的方法。如果我不需要,我不喜欢使用那个特定的事件,但由于我没有处理大量数据,所以效果很好。我在这个示例中唯一没有的是用于执行操作的命令。您可以在 DataContext 对象或其他机制上使用命令。
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
var contextMenu = new ContextMenu();
var deleteMenuItem = new MenuItem {Header = "Delete User"};
contextMenu.Items.Add(deleteMenuItem);
ContextMenuService.SetContextMenu(e.Row, contextMenu);
}
【讨论】: