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}" />
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章