且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建用于自定义控件的事件

更新时间:2023-10-13 21:34:04

这与为任何C#代码创建自定义事件没什么不同

this is no different than creating a custom event for any C# code

首先,在您的课程中创建一个公共事件和处理程序:

First, create a public event and handler in your class:

// note: you may want to create your own ImageEventArgs class that inherits from EventArgs
public delegate void ImageSelectedHandler(object sender, EventArgs e);
public event ImageSelectedHandler OnImageSelected;

下一步,在控件内部,您可以调用处理程序(如果存在)

next, inside the control you can call the handler if it exists

private void OnImageBtnTapped(object sender, EventArgs e)
{
  var tappedImage = (Label)sender;
  var ImageId = Convert.ToInt32(tappedImage.StyleId);
  Application.Current.Properties["ItemId"] = ImageId;

  MessagingCenter.Send(new RedirectClass.OpenRecordingDetails(), RedirectClass.OpenRecordingDetails.Key);

  // check if a handler is assigned
  if (OnImageSelected != null) {
    OnImageSelected(this,new EventArgs(...));
  }
}

最后,在使用控件的代码中,只需像通常那样定义事件处理程序即可

finally, in the code that is using the control, just define an event handler like you normally would

myControl.OnImageSelected += delegate {
  // handler logic goes here
};