Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have a UserControl that inside of another UserControl. Lets call them ParentUC and ChildUC. I need to get ParentUC from ChildUC.Can Anyone help me ,how to achieve this?

What I have tried:

Can anyone send me some links for this task.
Posted
Updated 25-Jul-16 9:38am

1 solution

Here an idea/way how you can solve your request to find the parent control.

Capture the parent control in OnVisualParentChanged:
C#
public partial class ChildUserControl : UserControl
{
    private ParentUserControl parentUserControl = null;

    protected override void OnVisualParentChanged(DependencyObject oldParent)
    {
        // Base Class
        base.OnVisualParentChanged(oldParent);

        // Parent Control
        parentUserControl = this.Parent as ParentUserControl;
    }

    // ....
    void DoSomethingWithParent()
    {
        // >>>Don't forget to check whether parent capturing was successful<<< 
        if (parentUserControl != null)
        {
           parentUserControl.ParentMethod();   
        }
    }
}


Parent Control XAML, note: child should not be in e.g. a grid for the code above.
XML
<usercontrol>
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication4" x:Class="MyWPFControls.ParentUserControl" 
             mc:Ignorable="d" Height="159.2" Width="209.6" Background="#FFD8BBBB">
    <local:childusercontrol horizontalalignment="Left" height="32" margin="147,117,0,0" verticalalignment="Top" width="53" xmlns:local="#unknown">

Background="#FFB28484"/>
</local:childusercontrol></usercontrol>

I hope it helps.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900