简体   繁体   中英

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?

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
}

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