Why click tree throws 'System.Windows.Documents.Run' is not a Visual or Visual3D' InvalidOperationException?

The issues reproduces when you click somewhere in the Label's text. In this case the e.OriginalSource will be a Run object which is a part of internal composition of the Label or TextBox. The Runelement is not inheriting from a Visual class, thus can't be a part of the visual tree, in this case the VisualTreeHelper.GetParent(source); will throw InvalidOperationException.

The easiest solution will be to make each text control (Label in your case) IsHitTestVisible="False", this will exclude these controls from hit testing logic, which means that it will never be the e.OriginalSource of an event, instead it's parent will be picked up and most likely the parent will be a Visual element.


I found that starting the search with the parent worked in my case. My TreeViewItem text consisted of several runs so I couldn't disable hit test.

    private void TextBlock_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        TreeViewItem treeViewItem;
        if (e.OriginalSource is System.Windows.Documents.Run)
            treeViewItem = VisualUpwardSearch(((System.Windows.Documents.Run)e.OriginalSource).Parent as DependencyObject);
        else treeViewItem = VisualUpwardSearch(e.OriginalSource as DependencyObject);

        if (treeViewItem != null)
        {
            treeViewItem.IsSelected = true;
            e.Handled = true;
        }
    }