Fork me on GitHub

UWP 区分设备类型

在写UWP应用时,通常会需要在代码里面判断当前是什么设备类型,以便在不同的设备上显示出不同的效果或者内容。

1. 通常我们都知道如何在C#代码里面去判断

public static DeviceFormFactorType GetDeviceFormFactorType()
        {
            switch (AnalyticsInfo.VersionInfo.DeviceFamily)
            {
                case "Windows.Mobile":
                    return DeviceFormFactorType.Phone;
                case "Windows.Desktop":
                    return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse
                        ? DeviceFormFactorType.Desktop
                        : DeviceFormFactorType.Tablet;
                case "Windows.IoT":
                    return DeviceFormFactorType.IoT;
                case "Windows.Team":
                    return DeviceFormFactorType.SurfaceHub;
                case "Windows.Xbox":
                    return DeviceFormFactorType.Xbox;
                case "Windows.Holographic":
                    return DeviceFormFactorType.Holographic;
                default:
                    return DeviceFormFactorType.Other;
            }
        }

 

2. Windows Community Toolkit也提供了一个简单粗暴的封装方式

using Microsoft.Toolkit.Uwp.Helpers;

// To get device family
public string DeviceFamily => SystemInformation.DeviceFamily;

 

3. XAML代码里面判断,也是Windows Community Toolkit提供的可以在XAML代码中直接使用的方式

xmlns:markup="using:Microsoft.Toolkit.Uwp.UI.Extensions.Markup"

<TextBlock Text="{markup:OnDevice Desktop=Desktop, Xbox=Xbox, Default=Default}" />
posted @ 2020-01-13 18:46  猫叔Vincent  阅读(302)  评论(0编辑  收藏  举报