Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF, how do I get the Data Object associated to the Tree View Item underneath the mouse cursor?

Tags:

wpf

treeview

In my WPF application, I have a treeview. This treeview is bound to a custom class (i.e. not TreeviewItems). So I use a hierarchicalDataTemplate to control how the tree renders.

When my mouse is over a tree view item, I would like to get the Data Object (i.e. my custom class instance) associated with the tree view item. How do I do this?

To clarify - I need the data object (not the UIElement) under the mouse cursor.

Assume my method to retrieve the data object has the following signature:

private object GetObjectDataFromPoint(ItemsControl source, Point point)
{
    ...
}
like image 813
willem Avatar asked Jul 07 '09 14:07

willem


2 Answers

Something like this (untested):

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;
}
like image 50
Kent Boogaart Avatar answered Nov 01 '22 15:11

Kent Boogaart


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;
}
like image 28
Musa Doğramacı Avatar answered Nov 01 '22 16:11

Musa Doğramacı