Events and Callbacks

Events provide hooks into the control’s behavior, allowing developers to respond to user interactions such as badge clicks, long presses, double taps, and badge update requests.

Overview

The Events feature exposes several public events in the control, including:

  • BadgeClicked: Fired when the notification badge is clicked.

  • LongPressed: Triggered when the button is held down beyond a predefined threshold.

  • DoubleTapped: Invoked when the button is tapped or clicked twice in quick succession.

  • BadgeUpdateRequested: Raised when an external update to the badge count is requested.

These events allow developers to extend the control's functionality by handling user interactions and integrating with application-specific logic.


Events and Their Configuration

The table below summarizes the key events provided by the control:

Event Name
Description
Event Handler Signature
Sample Usage Example

BadgeClicked

Occurs when the user clicks on the badge overlay.

EventHandler<EventArgs>

myButton.BadgeClicked += (s, e) => { /* handle badge click */ };

LongPressed

Occurs when the button is pressed and held for a specified duration (long press).

EventHandler<EventArgs>

myButton.LongPressed += (s, e) => { /* handle long press */ };

DoubleTapped

Occurs when the button is quickly double-clicked or double-tapped.

EventHandler<EventArgs>

myButton.DoubleTapped += (s, e) => { /* handle double tap */ };

BadgeUpdateRequested

Occurs when a badge update is requested, providing an opportunity to modify the badge count dynamically.

EventHandler<BadgeUpdateEventArgs>

myButton.BadgeUpdateRequested += (s, e) => { e.NewCount = 10; };

Note: The BadgeUpdateEventArgs class contains a property NewCount (an integer) and a flag Animate (a boolean) that allows control over how the badge is updated.


Key Points

Key Point
Details

Extendable Interaction

Events allow custom responses to user actions without modifying internal control logic.

Consistent Event Patterns

The events follow standard .NET event patterns, making them familiar and easy to integrate.

Fine-Grained Control

Developers can respond individually to badge clicks, long presses, double taps, and badge update requests.

Integration with Application Logic

Events enable the integration of business logic, such as triggering notifications, navigating to screens, or updating UI elements.


Best Practices

Best Practice
Description
Example Code Snippet

Subscribe Early

Subscribe to events during control initialization to ensure that all interactions are captured from the start.

csharp<br>myButton.BadgeClicked += MyBadgeClickHandler;<br>

Use Meaningful Handler Names

Name your event handler methods clearly (e.g., OnBadgeClicked, OnLongPressed) for maintainability and clarity.

csharp<br>private void OnLongPressed(object sender, EventArgs e)<br>{<br> // Handle long press<br>}<br>

Validate Event Arguments

Always check and validate the event arguments, especially for events like BadgeUpdateRequested where you modify values.

csharp<br>myButton.BadgeUpdateRequested += (s, e) => { if(e.NewCount < 0) e.NewCount = 0; };<br>

Unsubscribe When No Longer Needed

Remove event subscriptions to avoid memory leaks, especially in dynamic interfaces where controls may be created and destroyed at runtime.

csharp<br>myButton.LongPressed -= OnLongPressed;<br>


Common Pitfalls

Pitfall
Description
How to Avoid

Overlooking Event Subscription

Failing to subscribe to events may lead to missed user interactions and unintended behavior.

Ensure that your initialization code always subscribes to the necessary events.

Event Handler Performance Issues

Complex or long-running event handlers can block the UI thread, making the application unresponsive.

Offload heavy processing to background threads or use asynchronous patterns where appropriate.

Not Validating Badge Update Requests

Ignoring validation in BadgeUpdateRequested can result in invalid badge counts (e.g., negative numbers).

Validate and sanitize inputs within your event handler for BadgeUpdateRequested.

Memory Leaks from Persistent Subscriptions

Failing to unsubscribe event handlers when controls are disposed can lead to memory leaks.

Unsubscribe from events in the control's Dispose method or when the control is removed from the UI.


Usage Scenarios

Scenario
Description
Sample Integration Code

Notification Handling

When the badge is clicked, trigger a notification panel to open, or mark items as read.

csharp<br>myButton.BadgeClicked += (s, e) => { OpenNotificationPanel(); };<br>

Command Execution on Long Press

Use the long-press event to invoke secondary actions (e.g., showing a context menu) that are not available on a regular click.

csharp<br>myButton.LongPressed += (s, e) => { ShowContextMenu(); };<br>

Double-Tap to Toggle State

Implement double-tap behavior to toggle selection or switch modes, such as starting/stopping a process.

csharp<br>myButton.DoubleTapped += (s, e) => { ToggleButtonSelection(); };<br>

Dynamic Badge Update Requests

Update the badge count dynamically by handling BadgeUpdateRequested, perhaps by fetching new data from a server.

csharp<br>myButton.BadgeUpdateRequested += (s, e) => { e.NewCount = FetchNewBadgeCount(); e.Animate = true; };<br>


Real Life Usage Scenarios

Real Life Scenario
Description
Example Implementation

Email or Messaging Applications

In an email client, clicking the badge might open the inbox, while a long press could mark messages as read.

csharp<br>inboxButton.BadgeClicked += (s, e) => { OpenInbox(); };<br>inboxButton.LongPressed += (s, e) => { MarkAsRead(); };<br>

Social Media Notification Updates

For a social media app, double-tap might refresh the feed, and badge updates can dynamically show new notifications.

csharp<br>notificationButton.DoubleTapped += (s, e) => { RefreshFeed(); };<br>notificationButton.BadgeUpdateRequested += (s, e) => { e.NewCount = GetNewNotificationCount(); };<br>


Troubleshooting Tips

Issue
Potential Cause
Resolution

Event Not Firing

The event may not be firing if the control’s internal logic or hit-testing for badge or long press is misconfigured.

Verify that the control correctly detects user interactions and that event subscriptions are in place.

Handler Not Executing

An unhandled exception in an event handler might prevent subsequent handlers from executing.

Wrap event handler code in try-catch blocks and log exceptions to diagnose issues.

Incorrect Badge Count Update

When using BadgeUpdateRequested, if the event handler does not properly set the NewCount, the badge may not update correctly.

Validate the new count in your handler and ensure it conforms to expected values (e.g., non-negative).


Integration Code Sample

The following example demonstrates how to integrate and handle events in a simple WinForms application:

using System;
using System.Drawing;
using System.Windows.Forms;
using SiticoneNetFrameworkUI; // Ensure the correct namespace is referenced

public class MainForm : Form
{
    public MainForm()
    {
        // Initialize and configure a SiticoneGroupButton
        SiticoneGroupButton eventButton = new SiticoneGroupButton
        {
            Text = "Interactive Button",
            Size = new Size(220, 50),
            Location = new Point(20, 20),
            // Set other visual properties as needed
            NormalColor = Color.FromArgb(100, 100, 100),
            HoverColor = Color.FromArgb(80, 80, 80),
            PressColor = Color.FromArgb(50, 50, 50),
            SelectedColor = Color.Blue,
            TextColor = Color.LightGray,
            SelectedTextColor = Color.White,
            // Enable badge features if desired
            ShowBadge = true,
            BadgeCount = 3
        };

        // Subscribe to event handlers
        eventButton.BadgeClicked += (sender, e) =>
        {
            MessageBox.Show("Badge was clicked!");
        };

        eventButton.LongPressed += (sender, e) =>
        {
            MessageBox.Show("Button was long pressed!");
        };

        eventButton.DoubleTapped += (sender, e) =>
        {
            MessageBox.Show("Double tap detected!");
        };

        eventButton.BadgeUpdateRequested += (sender, e) =>
        {
            // For example, update the badge count from a data source
            e.NewCount = 5;
            e.Animate = true;
        };

        // Add the button to the form
        Controls.Add(eventButton);
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MainForm());
    }
}

Review

Review Aspect
Details

Extensibility

The events provide well-defined hooks that enable developers to extend the control’s functionality without altering internal code.

Ease of Use

Standard .NET event patterns make it simple to subscribe and handle events, reducing the learning curve for integration.

Responsiveness

Quick event firing in response to user interactions ensures a dynamic and engaging user experience.

Maintainability

Using clear and well-documented event handlers contributes to a maintainable and scalable codebase.


Summary

Summary Point
Description

Enhanced Interactivity

Events expose key user interactions (badge click, long press, double tap, badge update) that allow developers to integrate custom behavior.

Standard Event Patterns

Adheres to standard .NET event handling conventions, ensuring that integration is straightforward and familiar to developers.

Fine-Grained Control

Each event provides a specific trigger for user actions, allowing precise control over the application’s response to interactions.

Seamless Integration

The event-driven architecture integrates smoothly with other features of the control, contributing to an engaging and interactive UI.


Additional Useful Sections

Frequently Asked Questions (FAQ)

Question
Answer

How do I subscribe to these events?

Subscribe to events by adding an event handler method using the += syntax, for example: myButton.BadgeClicked += MyBadgeClickHandler;.

Can I update the badge count dynamically?

Yes, handle the BadgeUpdateRequested event and set the NewCount property on the provided BadgeUpdateEventArgs object to update the badge.

What should I do if an event handler causes delays?

Ensure that event handlers perform only lightweight operations, offloading heavy processing to background tasks if necessary.

Integration Checklist

Checklist Item
Status

Subscribe to Required Events

Ensure that each event (BadgeClicked, LongPressed, DoubleTapped, BadgeUpdateRequested) is subscribed to as needed.

Validate Event Arguments

Check that event arguments (e.g., NewCount) are validated and updated appropriately within handlers.

Test Interaction Scenarios

Test all interaction scenarios (click, long press, double tap) to confirm that events fire as expected.

Unsubscribe When Appropriate

Remove event handlers when controls are disposed to prevent memory leaks.


By following this comprehensive documentation for Events, developers can effectively integrate and handle user interactions in their .NET WinForms applications using the provided event hooks, ensuring that the control responds dynamically to various actions and enhances overall application interactivity.

Last updated