如何知道单击contextAction menuItem的listView viewCell?

时间:2015-01-16 19:31:07

标签: c# xaml listview xamarin cross-platform

我有一个在xaml中创建的listView(使用xamarin在线跨平台开发指南),如下所示:

<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>

我以编程方式分配ItemSource,如下所示:AccountsList.ItemsSource = App.Database.GetAccounts();

而这里是我的“删除”&#39;方法:

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

我希望能够知道单击了menuItem的特定viewCell,即引用&#39; DeviceName&#39;上面提到的对象&#39; onDelete&#39;方法。我知道我可以使用&#39; ItemSelected&#39; listView的方法如下:

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

但是&#39; Clicked&#39;方法不允许“OnDelete”(对象发送者,SelectedItemChangedEventArgs e)&#39;签名(我怀疑它会起作用)。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以绑定行的记录ID,类似于以下示例

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

在您的OnDelete事件处理程序中,您可以从CommandParameter获取我们之前绑定的记录ID,类似于以下示例,

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