0

What I want is to store a method with parameters owned by one class in a variable in another class for later execution. The first class would be my MainWindow class and second is a UserControl. The method I want to pass would stand in as a SelectionChanged event for a ListBox contained in the UserControl. The method would require a parameter only the UserControl will know at the time items are changing.

An example for my method (in MainWindow) would be as follows:

public void MethodToPass(string UniqueParameterValue) {
    //...do stuff with special string
}

And I would pass the method in my MainWindow class like:

//In MainWindow.Loaded
this.userControlInstance.SelectionChanged += MethodToPass;

Because I'm not directly assigning it to the ListBox, I would do so in the UserControl like:

private void selectionChanged;
public void SelectionChanged {
    get {
        ...
    } 
    set
    {
        this.selectionChanged = value;
        this.listBox1.SelectionChanged += value;
    }
}

I feel like NOT directly setting the ListBox is redundant, but my MainWindow class does not allow me to "see" it. I also feel like the more politically correct way to do this is to store the method in a variable, but I don't know how to do that or call it.

How are operations like this usually done?

  • So, you're trying to call a method in the main window class based on an event on the listbox in the user control with parameters that only the user control knows? Do I have that right? – ScoobyDrew18 Dec 17 '15 at 16:28
  • You can leverage Action and Action, as they are delegates. But it seems as though you have some misconceptions with event handling. Could you please share more code and further clarify what you are trying to do? – David Pine Dec 17 '15 at 16:28
  • @ScoobyDrew18 Yes, MainWindow contains an object called DocumentManager, which handles opening files and changing window UI based on file opened. The string parameter in MethodToPass is the path to the file we want to open and is owned by DocumentManager. The UserControl will get and return a bunch of files that we should be able to open and will pass a file path to the MethodToPass when the file is selected in the ListBox. Rather than copy DocumentManager's MethodToPass method and paste into UserControl, I would like to somehow be able to access it from the UserControl, if that makes sense. –  Dec 17 '15 at 16:34

1 Answers1

0

You should be able to expose the properties of your user control by creating them as class properties as usual. Then you can create an event on your user control which is raised by the SelectionChanged event of your ListBox. You can subscribe to this event using a delegate on your main window.

Check out these links: How to access properties of a usercontrol in C#

How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?

Community
  • 1
  • 1
ScoobyDrew18
  • 633
  • 9
  • 20