我可以根据条件禁用ViewCell.ContextActions吗?

ste*_*eaw 5 c# xaml listview xamarin xamarin.forms

嗨,我使用Xamarin Forms ListView,我想知道我是否可以基于某个绑定或后面的代码禁用上下文操作.

我在整个应用程序中使用一个GroupedListView,但它根据用户的操作显示不同的数据.有一个"管理您的收藏夹"功能,我希望用户能够在iOS上滑动删除或长按Android以删除ListItem,但如果列表显示一些搜索,我不希望这种行为结果或其他

<ViewCell.ContextActions>
    <MenuItem Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" Command="{Binding Path=BindingContext.OnDeleteCommand, Source={x:Reference Name=ListViewPage}}"/>
</ViewCell.ContextActions>
Run Code Online (Sandbox Code Playgroud)

这并没有禁用它......

<ViewCell.ContextActions IsEnabled="false"> //This IsEnabled does nothing
    <MenuItem Text="Delete" IsDestructive="true" CommandParameter="{Binding .}" Command="{Binding Path=BindingContext.OnDeleteCommand, Source={x:Reference Name=ListViewPage}}"/>
</ViewCell.ContextActions>
Run Code Online (Sandbox Code Playgroud)

如何禁用ContextActions?我不想让用户总是能够刷卡

ste*_*eaw 10

对于我想要实现的目标,我做了以下......

在XAML中

<ViewCell BindingContextChanged="OnBindingContextChanged">
Run Code Online (Sandbox Code Playgroud)

在后面的代码中

private void OnBindingContextChanged(object sender, EventArgs e)
{
    base.OnBindingContextChanged();

    if (BindingContext == null)
        return;

    ViewCell theViewCell = ((ViewCell)sender);
    var item = theViewCell.BindingContext as ListItemModel;
    theViewCell.ContextActions.Clear();

    if (item != null)
    {
        if (item.ListItemType == ListItemTypeEnum.FavoritePlaces
           || item.ListItemType == ListItemTypeEnum.FavoritePeople)
        {
            theViewCell.ContextActions.Add(new MenuItem()
            {
                Text = "Delete"
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

根据我们正在处理的列表项类型,我们决定在何处放置上下文操作


Ger*_*uis 6

有几种方法可以解决这个问题。

  1. 您可以根据自己的条件删除MenuItem表格ContextActions。这不能由纯 XAML 完成,您将不得不执行一些代码隐藏。
  2. 另一种选择是查看DataTemplateSelector. 这使您可以在运行时为 ViewCell(或 Cells)选择模板。在该模板中,您可以选择添加ContextActions或不添加。

  • 感谢您的帮助,我查看了 DataTemplateSelector,它看起来是我问题的一个很好的解决方案。我找到了另一种方法,通过在 ViewCell 上使用“BindingContextChanged” (2认同)