2016-06-29 43 views
3

嗨,我使用Xamarin表單ListView,我想知道是否可以禁用基於特定綁定的上下文操作或在後面的代碼中。我可以根據條件禁用ViewCell.ContextActions

我爲整個應用程序使用一個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> 

這並沒有禁用它...

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

我如何禁用ContextActions?我不希望用戶總是能夠滑動

回答

5

爲了什麼我想實現我做了以下...

在XAML

<ViewCell BindingContextChanged="OnBindingContextChanged"> 

在後面的代碼

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

基於該列表項的類型我們正在處理,我們可以決定在何處放置上下文動作

4

有幾種方法可以解決這個問題。

  1. 根據您的情況,您可以從ContextActions中刪除MenuItem。這不能由純XAML完成,你將不得不做一些代碼隱藏。
  2. 另一種選擇是看DataTemplateSelector。這使您可以在運行時爲您的ViewCell(或單元)選擇一個模板。在該模板中,您可以選擇添加或不添加ContextActions
+1

感謝您的幫助,我查看了DataTemplateSelector,它看起來像是我的問題的一個很好的解決方案。我在ViewCell – stepheaw

-2

只需禁用單元格工作,但僅適用於Android,不適用於iOS。在iOS和Android上使用Xamarin Forms(2.0.5782)項目進行測試。

<ViewCell IsEnabled="false"> 

請注意,它在ViewCell上,而不是ViewCell.ContextActions,就像您在示例中使用的那樣。

+1

上使用'BindingContextChanged'發現了另一種方法,但是您不能僅僅禁用它,因爲有條件需要檢查 – user3841581