Android 上的 VisualElement 提高許可權

Download Sample 下載範例

此 Android 平台專屬是用來控制以 API 21 或更新版本為目標之應用程式上視覺元素的提高許可權或 Z 順序。 視覺元素的提升會決定其繪製順序,而具有較高 Z 值的視覺元素會遮蔽具有較低 Z 值的視覺元素。 將附加屬性設定 VisualElement.Elevationboolean 值,以在 XAML 中取用:

<ContentPage ...
             xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
             Title="Elevation">
    <StackLayout>
        <Grid>
            <Button Text="Button Beneath BoxView" />
            <BoxView Color="Red" Opacity="0.2" HeightRequest="50" />
        </Grid>        
        <Grid Margin="0,20,0,0">
            <Button Text="Button Above BoxView - Click Me" android:VisualElement.Elevation="10"/>
            <BoxView Color="Red" Opacity="0.2" HeightRequest="50" />
        </Grid>
    </StackLayout>
</ContentPage>

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

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

public class AndroidElevationPageCS : ContentPage
{
    public AndroidElevationPageCS()
    {
        ...
        var aboveButton = new Button { Text = "Button Above BoxView - Click Me" };
        aboveButton.On<Android>().SetElevation(10);

        Content = new StackLayout
        {
            Children =
            {
                new Grid
                {
                    Children =
                    {
                        new Button { Text = "Button Beneath BoxView" },
                        new BoxView { Color = Color.Red, Opacity = 0.2, HeightRequest = 50 }
                    }
                },
                new Grid
                {
                    Margin = new Thickness(0,20,0,0),
                    Children =
                    {
                        aboveButton,
                        new BoxView { Color = Color.Red, Opacity = 0.2, HeightRequest = 50 }
                    }
                }
            }
        };
    }
}

方法 Button.On<Android> 會指定此平台專屬只會在Android上執行。 命名空間 VisualElement.SetElevation 中的 Xamarin.Forms.PlatformConfiguration.AndroidSpecific 方法可用來將視覺化專案的提高權限設定為可為 floatNull 的 。 此外, VisualElement.GetElevation 方法可以用來擷取視覺專案的提高許可權值。

結果是可以控制視覺元素的提升,讓具有較高 Z 值的視覺元素遮蔽具有較低 Z 值的視覺元素。 因此,在此範例中,第二個 Button 會轉譯在 上方 BoxView ,因為它具有較高的提高許可權值:

VisualElement elevation screenshot