翻譯變換
應用程式使用其中一個布局類 - StackLayout,Grid,AbsoluteLayout或RelativeLayout-在螢幕上定位可視元素。 讓我們将布局系統建立的位置稱為“布局位置”。
TranslationX和TranslationY屬性的非零值會更改可視元素相對于該布局位置的位置。 TranslationX的正值将元素向右移動,而TranslationY的正值将元素向下移動。
TranslationDemo程式允許您試驗這兩個屬性。 一切都在XAML檔案中:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TranslationDemo.TranslationDemoPage">
<StackLayout Padding="20, 10">
<Frame x:Name="frame"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand"
OutlineColor="Accent">
<Label Text="TEXT"
FontSize="Large" />
</Frame>
<Slider x:Name="xSlider"
Minimum="-200"
Maximum="200"
Value="{Binding Source={x:Reference frame},
Path=TranslationX}" />
<Label Text="{Binding Source={x:Reference xSlider},
Path=Value,
StringFormat='TranslationX = {0:F0}'}"
HorizontalTextAlignment="Center" />
<Slider x:Name="ySlider"
Minimum="-200"
Maximum="200"
Value="{Binding Source={x:Reference frame},
Path=TranslationY }" />
<Label Text="{Binding Source={x:Reference ySlider},
Path=Value,
StringFormat='TranslationY = {0:F0}'}"
HorizontalTextAlignment="Center" />
</StackLayout>
</ContentPage>
架構包含一個Label,并在StackLayout的上半部分居中。 兩個Slider元素綁定到Frame的TranslationX和TranslationY屬性,并且它們被初始化為-200到200的範圍。當您第一次運作程式時,兩個滑塊被設定為TranslationX和TranslationY的預設值, 為零:

您可以操縱滑塊以在螢幕上移動架構。 TranslationX和TranslationY的值指定元素相對于其原始布局位置的偏移量:
如果值足夠大,則可以将元素轉換為與其他視覺效果重疊,或者完全移出螢幕。
諸如Frame之類的元素的轉換也會影響該元素的所有子元素,在這種情況下,它隻是Label。您可以在任何VisualElement上設定TranslationX和TranslationY屬性,包括StackLayout,Grid,甚至Page及其派生詞。變換應用于元素和該元素的所有子元素。
沒有一點調查可能不那麼明顯的是,TranslationX和TranslationY僅影響元素的呈現方式。這些屬性不會影響布局系統中元素的感覺方式。
例如,VisualElement定義名為X和Y的get-only屬性,訓示元素相對于其父元素的位置。當元素由其父元素定位時,将設定X和Y屬性,在此示例中,Frame的X和Y屬性訓示Frame的左上角相對于StackLayout左上角的位置。設定TranslationX和TranslationY時,X和Y屬性不會更改。此外,隻有Bounds屬性 - 它将X和Y以及Width和Height組合在一個Rectangle中 - 也不會改變。修改TranslationX和TranslationY時,布局系統不會涉及。
如果您使用TranslationX和TranslationY将Button從其原始位置移動會發生什麼? Button是否響應其原始布局位置或新渲染位置的水龍頭?你會很高興知道它是後者。 TranslationX和TranslationY會影響元素的呈現方式以及它如何響應水龍頭。您很快就會在名為ButtonJump的示例程式中看到這一點。
如果需要在頁面周圍進行大量的元素移動,您可能想知道是否使用AbsoluteLayout并明确指定坐标或使用TranslationX和TranslationY來指定偏移。 在性能方面,實際上差别不大。 TranslationX和TranslationY的優點是你可以從StackLayout或Grid建立的位置開始,然後相對于該位置移動元素。