Home > Mobile >  How to set button click event handler in .Net Maui?
How to set button click event handler in .Net Maui?

Time:12-08

I have the following design in a page :

<CollectionView ItemsSource="{Binding Results}">                
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="viewmodel:MyViewModel">
            <Frame>                                                            
                <HorizontalStackLayout Grid.Column="1">
                    <Label Text="{Binding Title}"></Label> 
                    <Button Text="Do something" IsVisible="{Binding IsVisibleFlag}" CommandParameter="{Binding Identifier}" Clicked="ButtonClicked_EventHandler"></Button>                              
                </HorizontalStackLayout>                            
            </Frame>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

So it's basically a button bound to some results. Then I'm trying to catch the clicked EventHandler with a parameter as follows:

void ButtonClicked_EventHandler(object sender, EventArgs e)
{       
    ClickedEventArgs P = (ClickedEventArgs)e;   // << exception here

    string Identifier = P.Parameter.ToString();
    // Do something
}   

The button, the binding and the layout work just fine however when clicking the button, I'm having an exception in the line where I parse EventArgs into ClickedEventArgs to get the value of the parameter. I'm getting the error :

System.InvalidCastException : 'Unable to cast object of type 'System.EventArgs' to type 'Microsoft.Maui.Controls.ClickedEventArgs'.'

Does anyone know what I'm doing wrong please ?

Thanks.

CodePudding user response:

A CommandParameter, as the name implies, is intended to be used with a Command, not an event handler. However, you can do something similar like this

Button btn = (Button)sender;
var parameter = (string)btn.CommandParameter;
  • Related