1
votes

I have this listview

<ListView x:Name="LocationsListView" ItemsSource="{Binding ListOfFuel}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <StackLayout>
          <StackLayout>
            <Button CommandParameter="{Binding Id}" Clicked="Button_Clicked"></Button>
          </StackLayout>
        </StackLayout>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

With the code behind event I want to get the CommandParameter which is part of the ItemsSource list, the Id value.

I'm doing this:

private void Button_Clicked(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    int Idvalue = btn.Id;
}

With this approach the app is complaining that the button Id is guid value but in the list I have Id as integer, so I'm assuming the Id is some kind of identification for the button itself not the actual Id value from the items source.

What are my options to find out on button click the listview id or some other property in that list?

2
The problem is that CommandParamter is used for Commands while you're using the Clicked event handler. You can check this post: stackoverflow.com/a/50912352/10608418. To see how you can extract the value of the CommandParameter inside an event handler. But in my opinion the cleaner way is to use a Command instead of the Clicked event.user10608418

2 Answers

2
votes

You can only get the CommandParameter in Command .

In xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="xxx.MainPage"
             x:Name="contentPage">//set the name of contentPage here
<StackLayout>
         <Button CommandParameter="{Binding Id}" Command="{Binding Source={x:Reference contentPage}, Path=BindingContext.ClickCommand}"></Button>
</StackLayout>

And in your ViewModel:

public ICommand ClickCommand { get; set; }

//...

public MyViewModel()
{
   //...

   ClickCommand = new Command((arg)=> {

    Console.WriteLine(arg);

  });
}

arg here is the CommandParameter that you binding the value of property Id

0
votes

I can give you two solutions to this. 1. Instead of using a Button inside Nested StackLayout you can use ItemSelected Event of Listview. In that method you can get the entire Item using e.SelectedItem and the cast it to your class type

ListView.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
    var item = (YourClass) e.SelectedItem;

    // now you can any property of YourClass.  
};
  1. You can find the highest Parent and then get it's BindingContext.

    private void Button_Clicked(object sender, EventArgs e) { StackLayout stc = ((sender as Button).Parent as StackLayout).Parent as StackLayout; // Then get the BindingContext

    }