如何在用户控件上单击按钮执行包含窗口中的方法?控件、单击、按钮、方法

2023-09-07 15:44:27 作者:一笔朱砂

我有一个 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.

本教程解释的非常清楚.