WPF call method parent from usercontrol
Asked Answered
U

2

6

I want to call a method from user control in WPF

I´ve a Window with a list and I have a method that get this list.

private ObservableCollection<int> _lst;

public MainWindow()
{
     InitializeComponent();

     getList();
    }

public void getList()
{
    _lst = List<int>(); 
}

In this page I use a usercontrol:

UserControlAAA userControl = new UserControlAAA ();

gridDatos.Children.Add(userControl);

I want to do something like this inside of usercontrol:

Window win = Window.GetWindow(this);

win.getList();

but I can´t call win.getList();

I want to call the method getList from my usercontrol, but I don´t know how to do it.

Unorganized answered 23/2, 2014 at 22:29 Comment(0)
C
9

You'll need to cast the Window object to the specific window type you're using - which in your case is MainWindow:

MainWindow win = (MainWindow)Window.GetWindow(this);
win.getList();

However, it's not wise to have such coupling between the user control and the window it's hosted in, since that means you will only be able to use it in a window of type MainWindow. It would be better to expose a dependency property in the user control and bind the list to that property - this way the user control will have the data it requires and it will also be reusable in any type of window.

Cattleya answered 23/2, 2014 at 22:44 Comment(0)
H
0

Solution from @Adi Lester is working but it break WPF coding ruler. Proper way of doing this is using event like in the linked answer below https://mcmap.net/q/1774158/-how-to-access-parent-class-function-control-from-a-child-user-control-loaded-in-a-pannel

Homager answered 10/4, 2020 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.