简体   繁体   中英

Raise event in a User Control to MainWindow

Sorry first, because I see another question, but both of the ans. and ques. is not clear enough How can I raise a parent event from a user control in WPF?

In my MainWindow.xaml, I had a right Panel

<local:RightSideContent x:Name="RightPanel"  Grid.Column="1">

So in the MainWindow.xaml.cs, if I want rise an event to this panel, I made the code like this:

public delegate void Event1();
public MainWindow()
{
    this.InitializeComponent();
    Event1 obj = new Event1(this.RightPanel.func);
    obj();
    // Insert code required on object creation below this point.        
}

And in RightPanel class, I declare the function func

The question is: if I am in the RightPanel Class, how I raise an event to the MainWindow, because I can't wrote something like this.RightPanel.func.....

And by the way I am in another class that do not have xaml file, if I want raise an event to a UserControl, how can I do?

Sorry, I don't quite have enough rep to post a comment to clarify, but as I see it, there are three possible things you are trying to do here.

  1. You are trying to trigger an event on MainWindow, from some code that doesn't reside in MainWindow. In which case, you need to make sure that you have a reference to MainWindow, and that there is a public method on MainWindow that will trigger that event.

  2. You want MainWindow to handle a click etc that comes from RightPanel. In that case you simply put a Button.Click="blah" (or whatever the event is) attribute on your MainWindow, and it will catch any button clicks from below it that are not handled lower down. In fact you can even handle it lower down and make sure that you set the EventArgs so that it is effectively unhandled, so that you can then handle it higher up as well.

  3. You want to be able to handle a custom event generated in RightPanel, in a similar way to the way you would the button click scenario from item 2 above. In this case, I would direct you to http://msdn.microsoft.com/en-us/library/ms742806.aspx which is the documentation for Routed Events in WPF, and you should be able to work out how to create your own RoutedEvent from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM