Trigger Clicked Event of Button in Maui

136 views Asked by At

My platform is Windows.

Is it possible that I can trigger Clicked event in code?

In WPF, I was using RaisEvent to do it.

Like:

public void TriggerClickedEvent(UIElement element)
{
    element.RaiseEvent(
        new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Middle)
        {
            RoutedEvent = Mouse.PreviewMouseDownEvent,
            Source = element
        });
    element.RaiseEvent(
        new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Middle)
        {
            RoutedEvent = Mouse.PreviewMouseUpEvent,
            Source = element
        });
    element.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
}

But I have no idea how to do it In Maui.

1

There are 1 answers

0
Alexandar May - MSFT On

You can use the Model-View-ViewModel (MVVM) pattern to trigger the click event by writing a View Model with a command that performs whatever the logic would be done when clicking the Button. The ViewModel defines properties of type ICommand that are then connected to Button objects with data bindings. .NET MAUI also defines Command and Command classes that implement the ICommand interface and assist the viewmodel in defining properties of type ICommand.

Here's the sample below for your reference:

XAML:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ButtonDemos"
             x:Class="ButtonDemos.BasicButtonCommandPage"
             Title="Basic Button Command">
    <ContentPage.BindingContext>
        <local:CommandDemoViewModel />
    </ContentPage.BindingContext>

    <StackLayout>
        <Label Text="{Binding Number, StringFormat='Value is now {0}'}"
               FontSize="18"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
        <Button Text="Multiply by 2"
                VerticalOptions="Center"
                HorizontalOptions="Center"
                Command="{Binding MultiplyBy2Command}" />
    </StackLayout>
</ContentPage>

ViewModel:

public class CommandDemoViewModel : INotifyPropertyChanged
{
    double number = 1;

    public event PropertyChangedEventHandler PropertyChanged;

    public ICommand MultiplyBy2Command { get; private set; }
   
    public CommandDemoViewModel()
    {
        MultiplyBy2Command = new Command(() => Number *= 2);
    }

    public double Number
    {
        get => number;

        set
        {
            if (number != value)
            {
                number = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Number"));
            }
        }
    }
}