locked
Add a "Click" event to a class RRS feed

  • Question

  •  Hi! Im trying to face how to add to a class, a Click event, I mean, when i click on an instance of that class, i want to fire some event, which i want to handle. Im coding in VB so i´d rather the code in that language. Thanks for your help!

    Thursday, January 28, 2010 10:34 AM

Answers

  • If you're defining your own user control and not just a button, your class obviously has to have some sort of element the user can interact with visually.  all you'd really do is wire up the correct mouse event(s) to the interactable element, and then raise your own event.

    for example if you have a basic rectangle covering your entire user control that the user can 'click', just do something like this:

    Private WithEvents myRectangle As New Rectangle()
    Public Event MyCustomClickEvent(sender As Object) ' you can define additional arguments if you want

    Public Sub New()
        ' define your rectangle's dimensions, etc
    End Sub

    Private Sub myRectangle_MouseLeftButtonUp() Handles myRectangle.MouseLeftButtonUp
        RaiseEvent MyCustomClickEvent(Me)
    End Sub

    Thursday, January 28, 2010 10:53 AM

All replies

  •  If you mean handle a click on a control like a Button then in the XAML for the Button add the Click attribute and in the value state the name of your event handler like so:

      <Button x:Name="Button" Content="Click Me!" Click="Button_Click"/>

     and then in your code behind file for the XAML write your handler:

      Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
          'Do something interesting
      End Sub
    
      
    Thursday, January 28, 2010 10:46 AM
  • If you're defining your own user control and not just a button, your class obviously has to have some sort of element the user can interact with visually.  all you'd really do is wire up the correct mouse event(s) to the interactable element, and then raise your own event.

    for example if you have a basic rectangle covering your entire user control that the user can 'click', just do something like this:

    Private WithEvents myRectangle As New Rectangle()
    Public Event MyCustomClickEvent(sender As Object) ' you can define additional arguments if you want

    Public Sub New()
        ' define your rectangle's dimensions, etc
    End Sub

    Private Sub myRectangle_MouseLeftButtonUp() Handles myRectangle.MouseLeftButtonUp
        RaiseEvent MyCustomClickEvent(Me)
    End Sub

    Thursday, January 28, 2010 10:53 AM