Windows Phone開發之路(11) 方向處理之動態布局


  Silverlight應用程序默認運行在豎屏模式下,當手機改變方向時,如果想讓我們的應用程序可以隨着方向的改變自動作出響應,只需要在MainPage.xaml的PhoneApplicationPage標記中將屬性SupportedOritentations的值修改就可以了,它的值是枚舉類型,值為Portrait,Landscape或PortraitOrLandscape。

  處理動態布局時最重要的兩個屬性是HorizontalAlignment和VerticalAlignment。下面是一個例子,它將9個TextBlock元素放在一個Grid元素中,以展示Grid的HorizontalAlignment和VerticalAlignment在9種不同組合下的用法。

  XAML代碼:

<phone:PhoneApplicationPage 
x:Class="dtLayout1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"
shell:SystemTray.IsVisible="True">

<!--LayoutRoot 是包含所有頁面內容的根網格-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<TextBlock Text="Top-Left" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBlock Text="Top-Center" HorizontalAlignment="Center" VerticalAlignment="Top"/>
<TextBlock Text="Top-Right" HorizontalAlignment="Right" VerticalAlignment="Top"/>
<TextBlock Text="Center-Left" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Text="Center" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Text="Center-Right" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBlock Text="Bottom-Left" HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
<TextBlock Text="Bottom-Center" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
<TextBlock Text="Bottom-Right" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
</Grid>
</phone:PhoneApplicationPage>

  效果如圖:

   
        豎直方向                        水平方向

  在Silverlight的布局系統中,Margin(外邊距)屬性也非常重要,Margin屬性是Thickness類型的,Thickness是一個有Left,Top,Right,Bottom四個屬性的結構體,一般情況下我們都會指定四個數值,分別表示左,上,右,下邊距。當然在XAML中也可以指定一個數值,它表示四個邊距都為這個值,如果指定2個數值,那么它們分別代表距左右,上下的邊距。下面例子給上面程序中第5個TextBlock添加Margin屬性。

  XAML代碼:

<TextBlock Text="Center" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="100,200,50,300"/>

  效果如圖:

  我們可以看到,Text為Center的TextBlock不再居中了。

  以上就是今天總結的內容,主要有三個重要屬性,分別是HorzontalAlignment,VerticalAlignment和Margin。在實際的應用中,我們要靈活運用這三個屬性。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM