如何在 WPF 中为用户控件创建用户定义(新)事件?一个小例子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13447940/
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-08 23:34:35  来源:igfitidea点击:

How to create user define (new) event for user control in WPF ?one small example

wpfeventsuser-controls

提问by Kiranaditya

I have one UserControlin which I am using a Canvas, and in that Canvas one Rectangle. I want to create a click event for that user control (Canvas and Rectangle) which I then want to use in the main window.

我有一个UserControl,我在其中使用了一个Canvas,在那个画布中使用了一个矩形。我想为该用户控件(画布和矩形)创建一个单击事件,然后我想在主窗口中使用它。

The question is: I want to create a new click event for the UserControl. How to do it? Kindly show little example or the code.

问题是:我想为UserControl. 怎么做?请展示小例子或代码。

回答by Blachshma

A briefexample on how to expose an event from the UserControl that the main window can register:

简要如何从该用户控件,主窗口可以注册暴露事件例如:

In your UserControl:

在您的用户控件中:

1 . Add the following declaration:

1 . 添加以下声明:

public event EventHandler UserControlClicked;

2 . In your UserControl_Clicked event raise the eventlike this:

2 . 在您的 UserControl_Clicked 事件中引发这样的事件

 private void UserControl_MouseDown(object sender, MouseButtonEventArgs e)
 {
        if (UserControlClicked != null)
        {
            UserControlClicked(this, EventArgs.Empty);
        }
  }

In your MainWindow:

在您的 MainWindow 中

Your usercontrol will now have a UserControlClickedevent which you can register to:

您的用户控件现在将有一个UserControlClicked您可以注册的事件:

<local:UserControl1 x:Name="UC" UserControlClicked="UC_OnUserControlClicked" />

回答by DAkbariSE

i find this easier for passing value to handler:

我发现将值传递给处理程序更容易:

public event Action<string> onUserCodeFetched;

private void btnEnterClicked(object sender, RoutedEventArgs e)
        {
            onUserCodeFetched(PersonellCode.Text);
            PersonellCode.Text = "";
        }