在寫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}" />