Reputation: 13
Basically I have two main components to my program.
1) I have my main window which contains my dynamically created user controls.
2) The two different types of user controls.(ctr1 and ctr2)
I want to be able to press a button on ctr1, have it bubble up an event and have the main window handle the event which will create another instance of ctr2. The problem I am having is that I honestly can't find any good resources that gives actual code examples of how to accomplish this.
In ctr1 I have:
public event RoutedEventHandler MyEvent
{
add { AddHandler(MyEvent_randomName, value); }
remove { RemoveHandler(MyEvent_randomName, value); }
}
void RaiseMyEvent()
{
RoutedEventArgs newEventArgs = new RoutedEventArgs(ctr1.MyEvent_randomName);
RaiseEvent(newEventArgs);
}
protected override void RaiseEvent_click()
{
RaiseMyEvent();
}
and for my mainWindow I have:
public MainWindow()
{
InitializeComponent();
MainWindow.AddHandler(ctr1.MyEvent_randomName, new RoutedEventHandler(MyButtonHandler));
}
void MyButtonHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show("My New Clicked Event");
}
Where I have been running into trouble is the "MainWindow.AddHandler(ctr1.MyEvent_random......);
I keep getting the error:
An object reference is required for the non-static field, method, or property 'System.Windows.UIElement.AddHandler(System.Windows.RoutedEvent, System.Delegate)'
Im sorry if this is a very beginner question but I only started WPF and C# a few days ago and I have yet to find a good online tutorial that explains everything plainly.
Upvotes: 1
Views: 394
Reputation: 463
You can try this :
In ctr1
public event EventHandler Ctrl1ClickEvent;
when you press the button in ctrl1
Ctrl1ClickEvent(this, EventArgs.Empty);
In mainWindow
public MainWindow()
{
InitializeComponent();
this.ctrl1.Ctrl1ClickEvent += ctrl1ClickHandler;
}
private void ctrl1ClickHandler(object sender, EventArgs e)
{
MessageBox.Show("My New Clicked Event");
}
Upvotes: 0
Reputation: 2037
Check the error:
An object reference is required for the non-static field, method, or property 'System.Windows.UIElement.AddHandler(System.Windows.RoutedEvent, System.Delegate)'
You are trying to access the method statically:
MainWindow.AddHandler . . .
When you should be doing:
AddHandler . . .
As an aside you may want to look at ICommand and MVVM to do what you want to do, but as a beginner you have a lot to learn right now ;)
Upvotes: 2