J4N
J4N

Reputation: 20771

How to get the parent of a UserControl hosted in a ContentControl?

In a WPF application, I've a ContentControl. In this ContentControl, I've a View.

Starting from a specific UserControl, I'm trying to go up in its logical tree, and "Activate" every component on the way. By example, if one parent is a Tab, I select it by example.

My issue is that when my UserControl is in a ContentControl, when I call the LogicalTreeHelper.GetParent(...) I receive null:

    private static void Activate(FrameworkElement frameworkElement)
    {
        //Here, in one iteration, I receive null when it's supposed to be the `ContentControl`.
        DependencyObject parent = LogicalTreeHelper.GetParent(frameworkElement); 
        if (parent is FrameworkElement parentFrameworkElement) 
        {
            Activate(parentFrameworkElement);
        }

        if (frameworkElement is DXTabItem tab)
        {
            tab.IsSelected = true;//If it's a  tab, it gets activated
        }

        frameworkElement.Focus();
    }

My Xaml is something like this:

<dx:DXTabControl AllowMerging="True" TabContentCacheMode="None" Margin="0,3,0,0">
    <dx:DXTabItem Header="Some channel">
        <local:SomeControl Channel="{Binding Channel}"/>
    </dx:DXTabItem>
    <dx:DXTabItem Header="Some other view">
        <ContentControl Content="{Binding Channel, Converter={StaticResource SomeModelToViewModelConverter}}" ContentTemplateSelector="{StaticResource ConventionBasedDataTemplateSelector}" />
    </dx:DXTabItem>
</dx:DXTabControl>

So: Any idea how to get the ContentControl from the control inside it?

Edit It seems to be related to the fact that the control is in an unselected tab(the goal of my feature IS to activate the tab in which a usercontrol bound to something is located).

Upvotes: 0

Views: 1124

Answers (1)

mm8
mm8

Reputation: 169420

Provided that the elements have been loaded and added to the visual tree, you could use the following recursive method to find the parent element:

private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    var parent = VisualTreeHelper.GetParent(dependencyObject);

    if (parent == null) return null;

    var parentT = parent as T;
    return parentT ?? FindParent<T>(parent);
}

Sample usage:

DXTabItem parent = FindParent<DXTabItem>(frameworkElement); 

Upvotes: 3

Related Questions