上下文操作菜单项在iOS PCL项目中不起作用

时间:2016-12-26 17:07:36

标签: c# ios xamarin

我在PCL项目中创建一个动态菜单,在列表视图出现时构建它。

这是我的xaml:

  <ListView  x:Name="ListParceiros" RowHeight="60" ItemTapped="Parceiros_Tapped" Style="{StaticResource listViewGlobalStyle}">
    <ListView.ItemTemplate>
      <DataTemplate>
        <ViewCell Appearing="OnItemAppearing">
          <StackLayout Orientation="Horizontal" HorizontalOptions="Fill" BackgroundColor="#fff">
            <StackLayout Orientation="Vertical">
              <Label Text = "{Binding Nome}" FontSize="24" AbsoluteLayout.LayoutBounds="0.25, 0.25, 400, 40"/>
              <Label Text = "{Binding CpfCnpj}" AbsoluteLayout.LayoutBounds="50, 35, 200, 25"/>
            </StackLayout>
          </StackLayout>
        </ViewCell>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>

我的cs文件:

private void OnItemAppearing(object sender, EventArgs e)
{
    ViewCell theViewCell = (ViewCell)sender;
    var item = theViewCell.BindingContext as Pessoa;
    theViewCell.ContextActions.Clear();

    if (item != null)
    {
        var pessoaVinculo = _pessoaVinculoRepository.Get(w => w.PessoaId == item.PessoaId && w.NegocioId == App.CurrentUser.NegocioId);
        if (pessoaVinculo.NegocioAtivo)
        {
            var desativarAction = new MenuItem { Text = "Desativar", IsDestructive = true };
            desativarAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
            desativarAction.Clicked += DesativarParceiro;

            var servicoAction = new MenuItem { Text = "Serviços" };
            servicoAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
            servicoAction.Clicked += CallServicos;

            theViewCell.ContextActions.Add(desativarAction);
            theViewCell.ContextActions.Add(servicoAction);
        }
        else
        {
            var aceitarVinculoAction = new MenuItem { Text = "Aceitar Vinculo" };
            aceitarVinculoAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
            aceitarVinculoAction.Clicked += AceitarConvite;

            theViewCell.ContextActions.Add(aceitarVinculoAction);
        }
    }
}

当我尝试在Android中访问MenuItem时,它工作正常,但在iOS中,MenuItem无法正常工作。 我怎么能做这个工作?

1 个答案:

答案 0 :(得分:1)

这可以使用两个DataTemplate来解决,每个案例一个,每个都有所需的ContextActions,然后使用DataTemplateSelector来显示正确的DataTemplate。

创建您的DataTemplateSelector并覆盖OnSelectTemplate方法,返回正确的DataTemplate,具体取决于您的条件(在您的情况下为pessoaVinculo.NegocioAtivo)。

了解有关DataTemplateSelector的更多信息 https://developer.xamarin.com/guides/xamarin-forms/templates/data-templates/selector