Android 上的 ViewCell 內容動作

Download Sample 下載範例

根據預設Xamarin.Forms,從 4.3 開始,當 ViewCell Android 應用程式中的 定義中每個專案的內容動作時,會在變更中選取的專案ListViewListView時更新內容動作功能表。 不過,在舊版 Xamarin.Forms 的內容動作功能表中並未更新,而且此行為稱為 ViewCell 舊版模式。 如果 ListView 使用 DataTemplateSelector 來設定其 ItemTemplate 來自 DataTemplate 定義不同內容動作的物件,這個舊版模式可能會導致行為不正確。

此 Android 平臺特定會啟用 ViewCell 操作動作功能表舊版模式,以提供回溯相容性,以便在變更中選取的專案 ListView 時,不會更新操作動作功能表。 將可繫結屬性true設定ViewCell.IsContextActionsLegacyModeEnabled為 ,以在 XAML 中取用它:

<ContentPage ...
             xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core">
    <StackLayout Margin="20">
        <ListView ItemsSource="{Binding Items}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell android:ViewCell.IsContextActionsLegacyModeEnabled="true">
                        <ViewCell.ContextActions>
                            <MenuItem Text="{Binding Item1Text}" />
                            <MenuItem Text="{Binding Item2Text}" />
                        </ViewCell.ContextActions>
                        <Label Text="{Binding Text}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

或者,您可以使用 Fluent API 從 C# 取用它:

using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
...

viewCell.On<Android>().SetIsContextActionsLegacyModeEnabled(true);

方法 ViewCell.On<Android> 會指定此平台專屬只會在Android上執行。 命名空間 ViewCell.SetIsContextActionsLegacyModeEnabled 中的 Xamarin.Forms.PlatformConfiguration.AndroidSpecific 方法可用來啟用 ViewCell 操作動作功能表舊版模式,以便在變更中選取的專案 ListView 時,不會更新操作動作功能表。 此外, ViewCell.GetIsContextActionsLegacyModeEnabled 方法可用來傳回內容動作是否已啟用舊版模式。

下列螢幕快照顯示 ViewCell 已啟用內容動作的舊版模式:

Screenshot of ViewCell legacy mode enabled, on Android

在此模式中,儘管針對儲存格 2 定義了不同的操作選單項,但顯示的內容動作選單項與儲存格 1 和儲存格 2 完全相同。

下列螢幕快照顯示 ViewCell 已停用的內容動作舊版模式,這是預設 Xamarin.Forms 行為:

Screenshot of ViewCell legacy mode disabled, on Android

在此模式中,會針對儲存格 1 和儲存格 2 顯示正確的操作動作選單項。