在WPF中,如何获取与鼠标光标下方的树视图项关联的数据对象?

时间:2009-07-07 14:24:09

标签: wpf treeview

在我的WPF应用程序中,我有一个树视图。此树视图绑定到自定义(即 TreeviewItems)。所以我使用hierarchicalDataTemplate来控制树的呈现方式。

当我的鼠标在树视图项上时,我想获得与树视图项关联的数据对象(即我的自定义类实例)。我该怎么做?

澄清 - 我需要鼠标光标下的数据对象(不是UIElement)。

假设我检索数据对象的方法具有以下签名:

private object GetObjectDataFromPoint(ItemsControl source, Point point)
{
    ...
}

2 个答案:

答案 0 :(得分:6)

像这样(未经测试):

private object GetObjectDataFromPoint(ItemsControl source, Point point)
{
    //translate screen point to be relative to ItemsControl
    point = _itemsControl.TranslatePoint(point);
    //find the item at that point
    var item = _itemsControl.InputHitTest(point) as FrameworkElement;

    return item.DataContext;
}

答案 1 :(得分:2)

private object GetObjectDataFromPoint(ItemsControl source, Point point) 
{    
    //translate screen point to be relative to ItemsControl    
    point = source.TranslatePoint(point, source);    

    //find the item at that point    
    var item = source.InputHitTest(point) as FrameworkElement;   

    return item.DataContext;
}
相关问题