Can I disable ViewCell.ContextActions based on a condition

落爺英雄遲暮 提交于 2020-02-02 04:07:41

问题


Hi I using a Xamarin Forms ListView and I want to know if I can disable the Context Actions based on a certain binding or in the code behind.

I am using one GroupedListView for the whole application but it displays different data based on what the user is doing. There is a "Manage your Favorites" feature where I want the user to be able to swipe-to-delete on iOS or long-press on android to remove a ListItem, but I do not want this behavior if the list is displaying some search result or something else

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

This did not disable it...

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

How can I disable the ContextActions? I dont wan't the user to always be able to swipe


回答1:


For what I wanted to achieve I did the following...

In the XAML

<ViewCell BindingContextChanged="OnBindingContextChanged">

In the code behind

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

Based which type of list item we are dealing with, we get to decide where to place the context actions




回答2:


There are a couple of ways to go about this.

  1. You can remove the MenuItem form the ContextActions based on your conditions. This cannot be done by pure XAML, you're going to have to do some code-behind.
  2. Another option is to look at the DataTemplateSelector. This lets you select a template for your ViewCell (or Cells) at runtime. In that template you can choose to add the ContextActions or not.



回答3:


Simply disabling the cell works, but for Android only not iOS. Tested with a Xamarin Forms (2.0.5782) project on both iOS and Android.

<ViewCell IsEnabled="false">

Notice it is on the ViewCell and not the ViewCell.ContextActions like you have in your sample.



来源:https://stackoverflow.com/questions/38104352/can-i-disable-viewcell-contextactions-based-on-a-condition

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