⮪ Processing Entry Clicks

July 18, 2024 · View on GitHub

Once you've setup your DonutChartView you can react to segment clicks on the chart via ICommand or an event. Both approaches receive an object that represents the segment's associated entry class instance which is set by the underlying EntriesSource so that you can do what you need with the data.

Command Approach

On your DonutChartView you can bind the delegate you want to execute on click to the ICommand property, EntryClickedCommand. As mentioned previously, this command will receive an object parameter which is the clicked entry.

MVVM

In this example we're using a ViewModel setup with the CommunityToolkit.MVVM package to provide our entry clicked delegate which receives the clicked entry and casts to the type TestResult via pattern matching and displays its category and value as a toast.

internal sealed partial class SampleViewModel : BaseViewModel
{
    [RelayCommand]
    private static Task EntryClicked(object entry)
    {
        if (entry is not TestResult testResult)
        {
            return Task.CompletedTask;
        }

        string displayText = $"Entry \"{testResult.Category}\" with value {testResult.Score}, clicked!";
        IToast toast = Toast.Make(displayText, ToastDuration.Short, 14);
        return toast.Show();
    }
}

XAML

<donut:DonutChartView EntriesSource="{Binding TestResults}" EntryClickedCommand="{Binding EntryClickedCommand}" />

Code-Behind

MyChartView.EntryClickedCommand = viewModel.EntryClickedCommand;

Non-MVVM

private void OnEntryClicked(object entry)
{
    if (entry is not TestResult testResult)
    {
        return;
    }

    System.Diagnostics.Debug.WriteLine($"Entry \"{testResult.CategoryDisplay}\" with value {testResult.Score}, clicked!");
}

MyChartView.EntryClickedCommand = new Command(OnEntryClicked);

Event Approach

On your DonutChartView you can subscribe to the entry clicks and provide the delegate you want to execute on click to the event, EntryClicked. As mentioned previously, this event will receive an object argument which is the clicked entry.

Since both the XAML and Code-Behind approach will rely on the delegate being defined in the code-behind. Picture the following method setup in the code-behind.

private void OnEntryClicked(object? sender, EntryClickEventArgs e)
{
    if (e.Entry is not TestResult testResult)
    {
        return;
    }

    System.Diagnostics.Debug.WriteLine($"Entry \"{testResult.CategoryDisplay}\" with value {testResult.Score}, clicked!");
}

XAML

<donut:DonutChartView EntriesSource="{Binding TestResults}" EntryClicked="OnEntryClicked" />

Code-Behind

MyChartView.EntryClicked += OnEntryClicked;

Note

You should ensure that you manage subscriptions to the EntryClicked event in an optimal way to reduce the risk of memory leaks in your app. Read more here.