Home > DeveloperSection > Forums > How to execute method in parent user control from child in wpf?
lois waisbrooker
lois waisbrooker

Total Post:70

Points:494
Posted on    November-14-2014 10:42 PM

 WPF C#  XAML 
Ratings:


 1 Reply(s)
 919  View(s)
Rate this:

I have a user control named Display in MainWindow.xaml. Display user control itself has a custom class Workspace.cs in it like this:

<UserControl x:Class="Program.Main.Controls.Display.Display"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             xmlns:workspaces="clr-namespace:Program.Workspaces">

    <Border>

        <Grid>

            <workspaces:Workspace x:Name="MyWorkspace" ClipToBounds="True"/>

        </Grid>

    </Border>

</UserControl>

In my custom class that is Worskspace.cs I'm rising a MouseLeftButtonDown event, I want to execute the ThisCommandCameFromWorkspace method in Display.xaml.cs when rising this event.

What is the best approach to do this? And What is the easiest?

Updated:

In my Workspace.cs I have

public event Action MyEventHandler;

private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)

    {

            if (MyEventHandler!= null)

                MyEventHandler();

    }

Now I want to capture this in Display user control and execute a method of its code-behind.



Elena Glibart
Elena Glibart

Total Post:35

Points:128
Posted on    November-15-2014 3:15 AM

I'd suggest not to use Action as event delegate type, but instead use the common type EventHandler. And don't call it MyEventHandler as it is not a handler, but just the event:

public event EventHandler MyEvent;

private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{

    if (MyEvent != null)

    {

        MyEvent(this, EventArgs.Empty);

    }

}

Now you would easily attach a handler for the event in the Display's XAML (supported by Intellisense in Visual Studio):

<workspaces:Workspace ... MyEvent="Display_MyEvent"/>


Don't want to miss updates? Please click the below button!

Follow MindStick