How to know the listView viewCell whose contextAct

2019-08-07 11:46发布

问题:

I have a listView created in xaml (using the xamarin online cross-platform dev guide) like so:

<ListView x:Name="AccountsList" ItemSelected="AccountSelected">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell>
        <ViewCell.ContextActions>
            <MenuItem Clicked="OnEdit"     
               Text="Edit" />
            <MenuItem Clicked="OnDelete"     
               Text="Delete" IsDestructive="True" />
         </ViewCell.ContextActions> 
          <ViewCell.View>
              <StackLayout Orientation="Vertical"
                           HorizontalOptions="StartAndExpand">

                <Label Text="{Binding DeviceName}"
                       HorizontalOptions="CenterAndExpand"/>
              </StackLayout>
          </ViewCell.View>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

I'm assigning the ItemSource programmatically like so: AccountsList.ItemsSource = App.Database.GetAccounts ();

And here's my 'onDelete' method:

public void OnDelete (object sender, EventArgs e) { 
    var mi = ((MenuItem)sender); 
    DisplayAlert("Delete Context Action", mi.Command + " delete context action", "OK"); 
}

I want to be able to know the specific viewCell whose menuItem was clicked, i.e. to reference the 'DeviceName' of the object from the above 'onDelete' method. I know I can do this with the 'ItemSelected' method of a listView like this:

void AccountSelected(object sender, SelectedItemChangedEventArgs e)
{
    var _account = (Account)e.SelectedItem;
    // And access the account here.
}

But the 'Clicked' method doesn't allow a 'void OnDelete (object sender, SelectedItemChangedEventArgs e)' signature (and I doubt it would work anyways).

How can I accomplish this?

回答1:

You can bind record id of the row similar to the below example,

<MenuItem Clicked="OnDelete" Text="Delete" IsDestructive="True" CommandParameter="{Binding RecordIdentifier}"/>

And on your OnDelete event handler, you can get the record id we bind earlier from the CommandParameter similar to the below example,

public void OnDelete (object sender, EventArgs e) 
 { 
      var mi = ((MenuItem)sender); 
      DisplayAlert("Delete Context Action", mi.CommandParameter + " delete context action", "OK"); 
 }