Home > Back-end >  Is there a way to add button on item in listview in MAUI?
Is there a way to add button on item in listview in MAUI?

Time:12-15

i need to add two button on each item in listview in MAUI but i still dont find a correct answer, any idea ?

<ListView x:Name="friendList" ItemsSource="{Binding Friends}" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding userName}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I want to add the button "Accept" and "Decline" next to the username because it will be a list of friend request

CodePudding user response:

You can use a ViewCell with a Grid or StackLayout inside the <DataTemplate>:

<ListView x:Name="friendList" ItemsSource="{Binding Friends}" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Label Text="{Binding userName}" />
                    <Button Text="Accept" />
                    <Button Text="Decline" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

You'll need to add the commands or event handlers for the buttons yourself.

CodePudding user response:

Based on your question,you can also consider achieving it by adding context menus.

ListView supports context menus items, which are defined as MenuItem objects that are added to the ViewCell.ContextActions collection in the DataTemplate for each item. The MenuItem objects are revealed when an item in the ListView is right-clicked. You can use the following code:

<ListView x:Name="friendList" ItemsSource="{Binding Friends}" >
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
             <ViewCell.ContextActions>
                <MenuItem Text="Accept"
                          Command="{Binding Source={x:Reference friendList}, 
                          Path=BindingContext.AcceptCommand}"
                          CommandParameter="{Binding}" />
                <MenuItem Text="Decline"
                          Command="{Binding Source={x:Reference friendList}, 
                          Path=BindingContext.DeclineCommand}"
                          CommandParameter="{Binding}" />
            </ViewCell.ContextActions>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>
</ListView>

Of course, you can also use event handlers for the menuitem.

  • Related