How to know the listView viewCell whose contextAction menuItem is clicked?

那年仲夏 提交于 2019-12-24 10:48:45

问题


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"); 
 }


来源:https://stackoverflow.com/questions/27991411/how-to-know-the-listview-viewcell-whose-contextaction-menuitem-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!