Click here to Skip to main content
11,802,442 members (70,912 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C# WPF User-controls
explanation of the application:

I have a main wpf windows containing "add_button" and "view-list" button and a "content_grid" .When the user clicks the "add_button" the control containing the add form is displayed in the "content_grid" , the same when he clicks view list he gets the usercontrol containing the list + add button.

The problem that i met:

To do that i have a method in my main_window show_control(control c) that gets the control and displays it in the "content_grid". the problem is that i want to display the "add_control" from the "list_control" (the user clicks "add_btn" that is in the "list_control" to display "add_control").

Thank you in advance Smile | :)
Posted 2-Jan-12 22:12pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1


Use delegate in your User Control

For example you got a button named "Add" on your control:

public partial class Test : UserControl
    public Test()
    public delegate void RunMethodHandler(object sender);
    public event RunMethodHandler RunMethod;
    private void Add_Click(object sender, RoutedEventArgs e)
        if (RunMethod != null)

Then in your MainWindow, Add the UserControl to MainWindow. I did and renamed it to "MyControl", then:

public MainWindow()
    MyControl.RunMethod +=new Test.RunMethodHandler(TestMethod);
public void TestMethod(object sender)

At last, when you Click on Add, the TestMethod() will run.

Good luck.
Amir Mahfoozi at 3-Jan-12 5:41am
+5 Good answer.
Shahin Khorshidnia at 3-Jan-12 5:52am
Thank you Amir jan.
csprogrammer at 3-Jan-12 6:20am
Thank you for the reply but I'm using
to Add the UserControl to main_Window.
Shahin Khorshidnia at 3-Jan-12 9:52am
Ok, Do not add the handler in Constructor (MainMenu.)

Add it after: content_grid.Children.Add(UserControl);For example:


UserControl.RunMethod +=new Test.RunMethodHandler(TestMethod);

If any more question you can ask.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Thank you your answers were really helpful Big Grin | :-D
Shahin Khorshidnia at 4-Jan-12 6:16am
Your welcome ;)

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

  Print Answers RSS
0 OriginalGriff 445
1 KrunalRohit 366
2 F-ES Sitecore 295
3 Afzaal Ahmad Zeeshan 230
4 CPallini 230
0 OriginalGriff 2,950
1 Maciej Los 1,910
2 KrunalRohit 1,862
3 CPallini 1,645
4 Richard MacCutchan 1,157

Advertise | Privacy | Mobile
Web04 | 2.8.151002.1 | Last Updated 4 Jan 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100