简体   繁体   English

来自用户控件的 WPF 调用方法父级

[英]WPF call method parent from usercontrol

I want to call a method from user control in WPF我想从 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();但我不能调用 win.getList();

I want to call the method getList from my usercontrol, but I don´t know how to do it.我想从我的用户控件中调用 getList 方法,但我不知道该怎么做。

You'll need to cast the Window object to the specific window type you're using - which in your case is MainWindow :您需要将Window对象转换为您正在使用的特定窗口类型 - 在您的情况下是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 .但是,在用户控件和它所在的窗口之间进行这种耦合是不明智的,因为这意味着您只能在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.最好在用户控件中公开一个依赖属性并将列表绑定到该属性 - 这样用户控件将拥有它需要的数据,并且它也可以在任何类型的窗口中重用。

Solution from @Adi Lester is working but it break WPF coding ruler. @Adi Lester 的解决方案正在运行,但它破坏了 WPF 编码标尺。 Proper way of doing this is using event like in the linked answer below https://stackoverflow.com/a/19384953/3099317这样做的正确方法是使用如下链接答案中的事件https://stackoverflow.com/a/19384953/3099317

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM