pilixonis
pilixonis

Reputation: 11

How to use UserControl events to MainWindow

I am creating a WPF application using MVVM pattern.

In my application I have a mainwindow which works like main template of the app. I created a TreeView in a UserControl that works like a menu.

In the main window all the presentation is hosted in tab controls, so every item from my TreeView is actually a new tab.

The tab control is defined on the main window.

So my question is how can Iopen a new tab (press an item from TreeView) in my current tab control when the event handlers of the TreeView are on the UserControls code behind file and not in the main window file and so I cannot interact with it?

Is it possible somehow to host the event handlers of the TreeView in the code-behind file of the main window?

Upvotes: 1

Views: 650

Answers (1)

jimSampica
jimSampica

Reputation: 12410

You should be able to do something like this

Usercontrol.xaml

<TreeView SelectedItemChanged="TreeViewHandler" />

Usercontrol.cs

public delegate void TreeViewSelectedItemHandler(object sender, RoutedPropertyChangedEventArgs<object> e);
public event TreeViewSelectedItemHandler TreeViewSelectedItemChanged;

private void TreeViewHandler(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    //Capture event from usercontrol and execute defined event
    if (TreeViewSelectedItemChanged != null)
    {
        TreeViewSelectedItemChanged(sender, e);
    }
}

Window.xaml

<local:myUsercontrol TreeViewSelectedItemChanged="myHandler" />

Window.cs

private void myHandler(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    //Do stuff
}

Upvotes: 1

Related Questions