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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21975549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:00:26  来源:igfitidea点击:

WPF call method parent from usercontrol

c#wpfmethodsuser-controlsparent

提问by user1253414

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 方法,但我不知道该怎么做。

回答by Adi Lester

You'll need to cast the Windowobject 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. 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.

但是,在用户控件和它所在的窗口之间进行这种耦合是不明智的,因为这意味着您只能在类型为 的窗口中使用它MainWindow。最好在用户控件中公开依赖项属性并将列表绑定到该属性 - 这样用户控件将拥有它需要的数据,并且它也可以在任何类型的窗口中重用。

回答by Sebastian Xawery Wi?niowiecki

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://stackoverflow.com/a/19384953/3099317

来自@Adi Lester 的解决方案正在发挥作用,但它破坏了 WPF 编码标尺。这样做的正确方法是使用如下链接答案中的事件 https://stackoverflow.com/a/19384953/3099317