C# 单击鼠标右键选择Silverlight Datagrid

C# 单击鼠标右键选择Silverlight Datagrid,c#,silverlight,datagrid,contextmenu,C#,Silverlight,Datagrid,Contextmenu,右键单击事件是否有办法在toolkit datagrid中选择一行 我使用的工具箱上下文菜单工作得很好,但问题是,只有左键单击才能选择行,如果我希望上下文菜单正常工作,我需要右键单击才能这样做 非常感谢您的帮助您可以找到解决方案 基本上是这样的: private void dg_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.MouseRightButtonDown += new MouseButtonEventHand

右键单击事件是否有办法在toolkit datagrid中选择一行

我使用的工具箱上下文菜单工作得很好,但问题是,只有左键单击才能选择行,如果我希望上下文菜单正常工作,我需要右键单击才能这样做

非常感谢您的帮助

您可以找到解决方案

基本上是这样的:

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;
}
<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);

    }

他的行为会为你带来好处(受此启发):

public类选择RowOnRightClickBehavior:Behavior
{
受保护的覆盖无效附加()
{
base.onatached();
AssociatedObject.MouseRightButtonDown+=HandlerRightButtonClick;
}
附加时受保护的覆盖无效()
{
base.OnDetaching();
AssociatedObject.MouseRightButtonDown+=HandlerRightButtonClick;
}
私有无效HandlerRightButtonClick(对象发送器,鼠标按钮Ventargs e)
{
var elementsUnderMouse=visualtreeheloper.FindElementsInHostCoordinates(e.GetPosition(null),AssociatedObject);
var row=elementsUnderMouse
第()类
.FirstOrDefault();
如果(行!=null)
AssociatedObject.SelectedItem=row.DataContext;
}
}
像这样使用它:

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;
}
<sdk:DataGrid x:Name="DataGrid" Grid.Row="4" 
                  IsReadOnly="True" 
                  ItemsSource="{Binding MyItems}">
        <i:Interaction.Behaviors>
            <b:SelectRowOnRightClickBehavior/>
        </i:Interaction.Behaviors>
</sdk:DataGrid>


很遗憾,我们不得不使用这样的黑客,但我认为这总比什么都没有好。感谢MouseRightButtonDown事件仅在SL 4.0中提供。在SL 3.0中是否有其他右键单击解决方案?