我在 PCL 项目中使 MenuItem 动态化,在 ListView 出现时构建它。
这是我的 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 不工作。 我怎样才能使它工作?
最佳答案
这可以使用两个 DataTemplate 来解决,每个案例一个,每个都有所需的 ContextActions,然后使用 DataTemplateSelector
显示正确的 DataTemplate。
创建您的 DataTemplateSelector
并覆盖 OnSelectTemplate
方法,根据您的条件返回正确的 DataTemplate(在您的情况下为 pessoaVinculo.NegocioAtivo
)。
了解更多关于 DataTemplateSelector 的信息 https://developer.xamarin.com/guides/xamarin-forms/templates/data-templates/selector
关于c# - 上下文操作菜单项在 iOS PCL 项目中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41334194/