如何在用户控件上单击按钮执行包含窗口中的方法? [英] How can a button click on a UserControl execute a method in the containing Window?
问题描述
我有一个 UserControl,我们称之为 myUC
,它是我的 WPF 应用程序的主窗口 (myWindow
) 中的几个 UserControl 之一.myUC
包含许多标准控件,其中一个是按钮,我们将其称为 myButton
.
I have a UserControl, we'll call it myUC
, that is one among several UserControls in the main window (myWindow
) of my WPF application. myUC
contains a number of standard controls, one of them being a button, we'll call it myButton
.
当我点击 myButton
时,我想执行 myMethod()
,它存在于 myWindow 的代码隐藏中.
When I click myButton
, I would like to execute myMethod()
, which exists in the code-behind of myWindow.
问题在于 myUC
根本不知道 myWindow
甚至存在,更不用说 myMethod 存在了.
The problem being that myUC
doesn't have any idea that myWindow
even exists, much less that myMethod exists.
我如何发送消息:'嘿,myWindow,醒来.myUc 上的 myButton 刚刚被点击;请运行 myMethod'?
How can I send the message: 'Hey, myWindow, wake up. myButton on myUc was just clicked; please run myMethod'?
推荐答案
可以在窗口中创建命令,并将按钮的Command属性设置为该命令的名称.单击按钮将触发命令,无需引用父窗口.
You can create a command in the window and set the Command property of the button to the name of this command. Clicking the button will fire the command, without a need for a reference to the parent window.
这篇关于如何在用户控件上单击按钮执行包含窗口中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!