In WPF, how do I get the Data Object associated to

2019-06-18 06:55发布

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)
{
    ...
}

标签: wpf treeview
2条回答
叼着烟拽天下
2楼-- · 2019-06-18 07:32

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;
}
查看更多
做个烂人
3楼-- · 2019-06-18 07:40
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;
}
查看更多
登录 后发表回答