| |
|
Call a parent method from UserControl using WPF in C#
|
| |
|
|
| |
| I was implemting some paging functionality in a system I was
building and realized that I had created the same forward, backward, first
and last buttons and logic 3 times. After doing this I realized these buttons
and logic were a perfect example of where I could reduce complexity and
encapsulate my code better. I wasn't able to easily find an example for a
situation I ran in to. I needed to call a method from the user control that
existed on the parent WPF window. After some trial and error I came up with
the below solution. |
| |
| In the User Control place the below logic. |
| |
public event EventHandler ExecuteMethod;
protected virtual void OnExecuteMethod()
{
if (ExecuteMethod != null) ExecuteMethod(this, EventArgs.Empty);
}
public void ChildButton_Click(object sender, EventArgs e)
{
OnExecuteMethod();
}
|
| |
| I first create an event and then a virtual method to call the event.
As you can see, when you want to execute an event, you need to pass it the
(object, sender) standard parameters. FInally, I had a button in the control,
that when pressed would execute the method that in turn executes the event. |
| |
| In the Parent WPF MainWindow, I added this code: |
| |
xmlns:Child="clr-namespace:className;assembly=assemblyName"
<Child:className Name="uc_Child" />
|
| |
| Within the opening Window tag, you need to place the reference to
your User Control. As well, add it to the references for the project. Then
add the tag to your WPF window where you want it displayed. |
| |
| In the Parent WPF code-behind, MainWindow.xaml.cs, I added
this code: |
| |
protected void ParentWPF_method(object sender, EventArgs e)
{
MessageBox.Show("ParentWPF_method called by ChildButton_Click",
"User Control Test", MessageBoxButton.OK,
MessageBoxImage.Asterisk);
}
public MainWindow()
{
InitializeComponent();
uc_Child.ExecuteMethod += new EventHandler(ParentWPF_method);
}
|
| |
| The ParentWPF_method is the method I want called / executed when
the ChildButton_Click occurs. For this example, it simply deploys a messagebox
saying that the method was successfully called. In the constructor of the
MainWIndow I "wire up" the User Controls' ExecuteMethod event to the
ParentWPF_method function. That is where the magic happens... |
| |
| I saw a number of other examples that seemed much more complex and
others that tightly coupled the user control and parent together. Both things I
wanted to avoid when implementing my solution. |
| |
|
|
| | |
| | | |