Silverlight 3 Datagrid:获取MouseOver上的行/项

时间:2009-12-08 10:52:36

标签: silverlight-3.0 datagrid selection mouseover

我有一个绑定的DataGrid和各种其他控件(在datagrid外部),它们显示了有关datagrid中selectedrow的更多详细信息。使用数据绑定或处理datagrid上的SelectionChanged事件很容易做到这一点。

但是,如何在不要求用户选择行的情况下执行此操作 - 例如,在“鼠标悬停”上,我可以更改所选项目或获取鼠标下的行/项目。

2 个答案:

答案 0 :(得分:3)

在容器类中尝试类似这样的事情,如UserControl,Grid,StackPanel等......

public class MyContainerClass : FrameworkElement
{
    public MyContainerClass()
    {
            base.Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        m_DataGrid.MouseMove += OnMouseMove;
    }

    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        DataGridRow item = (sender as DependencyObject).ParentOfType<DataGridRow>();
        if (item != null && m_DataGrid.SelectedIndex != item.GetIndex())
            m_DataGrid.SelectedIndex = item.GetIndex();
    }
}

并添加此辅助类扩展...

internal static class DependencyObjectExt
{
    // Extension for DependencyObject
    internal static TT ParentOfType<TT>(this DependencyObject element) where TT : DependencyObject
    {
        if (element == null)
            return default(TT);

        while ((element = VisualTreeHelper.GetParent(element)) != null)
        {
            if (element is TT)
                return (TT)element;
        }

        return null;
    }
}
祝你好运,
Jim McCurdy
YinYangMoney

答案 1 :(得分:2)

这是Jim的答案更简单但不太通用的实现。在VB.Net中:

Private Sub DataGrid1_LoadingRow(ByVal sender As Object, ByVal e As System.Windows.Controls.DataGridRowEventArgs) Handles DataGrid1.LoadingRow
    AddHandler e.Row.MouseEnter, AddressOf row_MouseEnter
End Sub

Private Sub row_MouseEnter(ByVal sender As Object, ByVal e As MouseEventArgs)
        Dim row = CType(sender, DataGridRow)
        Me.DataGrid1.SelectedItem = CType(row.DataContext, MyType)
End Sub