Device是一個靜態(tài)類,提供一些屬性和方法幫助開發(fā)者判斷平臺類型、對不同平臺提供不同處理。
Device.Idiom
Idiom屬性,TargetIdiom枚舉類型。可以根據(jù)Idiom判斷當前設備的類型。

使用方式,移動端開發(fā)主要判斷Phone和Tablet(平板):

Device.OS
OS屬性,TargetPlatform枚舉類型。判斷當前設備系統(tǒng)平臺。

如單獨設置iOS的Padding,解決頁面與狀態(tài)欄重疊問題:

Device.OnPlatform

Device提供了兩個OnPlatform方法。一個是范型方法,根據(jù)不同不同平臺,返回對應設置的值,內部通過判斷Device.OS屬性實現(xiàn)。

XAML使用示例:
<OnPlatform x:TypeArguments="Color"
iOS="Green"
Android="#738182"
WinPhone="Accent" />
還提供了一個接收Action類型參數(shù)的OnPlatform方法,會根據(jù)不同平臺執(zhí)行不同的動作。

OnPlatform does not currently support differentiating the Windows 8.1, Windows Phone 8.1, and UWP/Windows 10 platforms.
Device.Styles
提供了定義好的適用于Label樣式。包括:
- BodyStyle
- CaptionStyle
- ListItemDetailTextStyle
- ListItemTextStyle
- SubtitleStyle
- TitleStyle
不同平臺效果圖:

XAML使用示例:
<Label Text="TitleStyle" VerticalOptions="Center" HorizontalOptions="Center"
Style="{DynamicResource TitleStyle}" />
C#使用示例:
new Label
{
Text = "TitleStyle",
Style = Device.Styles.TitleStyle
};
Device.GetNamedSize
接收一個NamedSize類型參數(shù)和一個Type類型參數(shù),根據(jù)傳入的NamedSize返回當前平臺Type類型對應最適合的值。
var label = new Label();
label.FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label));
Device.OpenUri
根據(jù)傳入的Uri調用系統(tǒng)提供的內置功能。
打開網(wǎng)頁:
Device.OpenUri(new Uri("https://www.baidu.com/"));
撥打電話:
Device.OpenUri(new Uri("tel:10086"));
打開地圖定位:
if (Device.OS == TargetPlatform.iOS) {
//https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
Device.OpenUri(new Uri("http://maps.apple.com/?q=394+Pacific+Ave+San+Francisco+CA"));
} else if (Device.OS == TargetPlatform.Android) {
// opens the Maps app directly
Device.OpenUri(new Uri("geo:0,0?q=394+Pacific+Ave+San+Francisco+CA"));
} else if (Device.OS == TargetPlatform.Windows || Device.OS == TargetPlatform.WinPhone) {
Device.OpenUri(new Uri("bingmaps:?where=394 Pacific Ave San Francisco CA"));
}
Device.StartTimer
啟動一個簡單的定時器,每隔TimeSpan時間會執(zhí)行Func<bool>對應的動作。當Func<bool>返回false時,定時器停止。
創(chuàng)建一個周期為1秒的定時器:
Device.StartTimer(new TimeSpan(0, 0, 1), () =>
{
label.Text = DateTime.Now.ToString("F");
return true;
});
Device. BeginInvokeOnMainThread
用戶界面的相關操作是不允許在后臺線程中執(zhí)行。子線程中執(zhí)行用戶界面更新操作需要將代碼放在BeginInvokeOnMainThread中執(zhí)行,BeginInvokeOnMainThread作用類似于iOS中的InvokeOnMainThread, Android中的RunOnUiThread, Windows Phone中的Dispatcher.BeginInvoke。
Device.BeginInvokeOnMainThread(() =>
{
});