字元串格式
上一章中的一些示例程式使用事件處理程式來顯示Slider和Stepper視圖的目前值。如果您嘗試從Slider的Value屬性定義一個以Label的Text屬性為目标的資料綁定,您會發現它有效,但您無法對其進行太多控制。通常,您需要控制資料綁定中所需的任何類型轉換或值轉換。這将在本章後面讨論。
但是,字元串格式是特殊的。 Binding類具有StringFormat屬性,允許您包含整個.NET格式化字元串。幾乎總是,這種綁定的目标是Label的Text屬性,但綁定源可以是任何類型。
您提供給StringFormat的.NET格式化字元串必須适合調用String.Format靜态方法,這意味着它應包含占位符“{0}”,帶有或不帶有适合源資料類型的格式規範 - 例如“{0:F3}”顯示帶有三個小數位的double。
在XAML中,這個占位符有點問題,因為花括号可能會被誤認為用于分隔标記擴充的花括号。最簡單的解決方案是将整個格式字元串放在單引号中。
ShowViewValues程式包含四個顯示Slider,Entry,Stepper和Switch目前值的示例。用于顯示條目内容的格式字元串中的十六進制代碼是“智能引号”的Unicode ID:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ShowViewValues.ShowViewValuesPage"
Padding="10, 0">
<StackLayout>
<StackLayout VerticalOptions="CenterAndExpand">
<Label Text="{Binding Source={x:Reference slider},
Path=Value,
StringFormat='The Slider value is {0:F3}'}" />
<Slider x:Name="slider" />
</StackLayout>
<StackLayout VerticalOptions="CenterAndExpand">
<Label Text="{Binding Source={x:Reference entry},
Path=Text,
StringFormat='The Entry text is “{0}”'}" />
<Entry x:Name="entry" />
</StackLayout>
<StackLayout VerticalOptions="CenterAndExpand">
<Label Text="{Binding Source={x:Reference stepper},
Path=Value,
StringFormat='The Stepper value is {0}'}" />
<Stepper x:Name="stepper" />
</StackLayout>
<StackLayout VerticalOptions="CenterAndExpand">
<Label Text="{Binding Source={x:Reference switch},
Path=IsToggled,
StringFormat='The Switch value is {0}'}" />
<Switch x:Name="switch" />
</StackLayout>
</StackLayout>
</ContentPage>
使用StringFormat時,您需要特别注意逗号,單引号和花括号的位置。
這是結果:

您可能還記得第5章“處理大小”中的WhatSize程式。該程式在頁面上使用SizeChanged事件處理程式以與裝置無關的機關顯示螢幕的目前寬度和高度。
WhatSizeBindings程式在XAML中完成整個工作。 首先,它将x:Name屬性添加到根标記,以便為WhatSizeBindingsPage對象提供頁面名稱。 三個Label視圖在頁面中心共享一個水準StackLayout,其中兩個綁定到Width和Height屬性。 Width和Height屬性是get-only,但它們由可綁定屬性支援,是以它們在更改時觸發PropertyChanged事件:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="WhatSizeBindings.WhatSizeBindingsPage"
x:Name="page">
<StackLayout Orientation="Horizontal"
Spacing="0"
HorizontalOptions="Center"
VerticalOptions="Center">
<StackLayout.Resources>
<ResourceDictionary>
<Style TargetType="Label">
<Setter Property="FontSize" Value="Large" />
</Style>
</ResourceDictionary>
</StackLayout.Resources>
<Label Text="{Binding Source={x:Reference page},
Path=Width,
StringFormat='{0:F0}'}" />
<!-- Multiplication sign. -->
<Label Text=" × " />
<Label Text="{Binding Source={x:Reference page},
Path=Height,
StringFormat='{0:F0}'}" />
</StackLayout>
</ContentPage>
以下是本書使用的裝置的結果:
在縱向和橫向模式之間轉動手機時,顯示會發生變化。
或者,可以将StackLayout上的BindingContext設定為引用頁面對象的x:Reference标記擴充,并且不需要綁定上的Source設定。