Xamarin.Forms 每个平台的不同视图

tld*_*oon 6 xamarin.forms

所以我是 Xamarin 开发的新手,我有一个我无法找到答案的问题。是否可以实现一个视图,使其在每个平台甚至一个平台上看起来都不同?IE - 视图在 iOS 和 Android 上看起来相似,但对于 UWP 桌面应用程序,它可能有更多可用控件,因为有更多的屏幕空间。提前致谢。

Pau*_*her 8

当然可以。最简单的方法是在 XAML 中使用OnPlatform(参见此处)标记

<OnPlatform x:TypeArguments="View">
    <On Platform="iOS">
        <!-- Use view for iOS here -->
    </On>
    <On Platform="Android">
        <!-- Use view for Android here -->
    </On>
    <On Platform="UWP">
        <!-- Use view for UWP here -->
    </On>
</OnPlatform>
Run Code Online (Sandbox Code Playgroud)

在您的情况下(对 Android 和 iOS 使用相同的视图),您可以将其简化为

<OnPlatform x:TypeArguments="View">
    <On Platform="iOS, Android">
        <!-- Use view for iOS here -->
    </On>
    <On Platform="UWP">
        <!-- Use view for UWP here -->
    </On>
</OnPlatform>
Run Code Online (Sandbox Code Playgroud)

如果您在代码中创建视图,则可以使用 Device.RuntimePlatform

View CreateViewForCurrentPlatform()
{
    switch(Device.RuntimePlatform)
    {
        case Device.iOS:
        case Device.Android:
            return new View1();
        case Device.UWP:
            return new View2();
    }
    throw new Exception("Unsupported platform");
}
Run Code Online (Sandbox Code Playgroud)

反正既然你这么说了

[...] 对于 UWP 桌面应用程序,它可能有更多可用控件,因为有更多屏幕空间。

您应该考虑Device.Idiom改用(参见此处),它可以让您区分平板电脑、台式机和手机。Android 和 iOS 也在平板电脑上运行,在平板电脑上浪费屏幕空间会很可惜。