標籤:
就像在html中使用css一樣,在XAML元素中應用style可以對介面進行美化。
在控制項Resource屬性裡面建立樣式
<StackPanel> <StackPanel.Resources> <Style x:Key="commonStyle" TargetType="Button"> <Setter Property="Width" Value="200"></Setter> <Setter Property="Height" Value="15"></Setter> <Setter Property="FontSize" Value="20"></Setter> <Setter Property="Foreground" Value="Red"></Setter> <Setter Property="FontFamily" Value="Arial"></Setter> </Style> </StackPanel.Resources> <Button Style="{StaticResource commonStyle}">局部樣式</Button> </StackPanel>
在Resource中建立的樣式只能作用於局部,如上面樣式只能作用於StackPanel範圍內。有時我們希望建立的樣式在整個頁面都可以使用,那麼我們在Page節點下建立樣式
<Page.Resources> <Style TargetType="Button" x:Key="pageStyle"> <Setter Property="Width" Value="200"></Setter> <Setter Property="Height" Value="30"> </Setter> <Setter Property="Foreground" Value="Green"></Setter> </Style> </Page.Resources>
在做應用的時候我們不可能就一個介面,當多個頁面有公用的樣式,我們就需要建立一個讓每個介面都可以使用的樣式,而不是ctrl+c、ctrl+v。在App.xaml檔案中建立的樣式可以在整個應用程式中使用
<Application.Resources> <Style TargetType="Button" x:Key="outStyle"> <Setter Property="Width" Value="200"></Setter> <Setter Property="Height" Value="15"></Setter> <Setter Property="FontSize" Value="20"></Setter> <Setter Property="Foreground" Value="Blue"></Setter> <Setter Property="FontFamily" Value="Arial"></Setter> </Style> </Application.Resources>
如果程式比較大,介面比較多我們在使用上面方式建立樣式,就會使用程式在維護起來比較困難,這是我們就需要建立樣式檔案,就像在使用css時,把css樣式單獨放到一個檔案中一樣。在程式中添加一個ButtonStyle.xaml樣式檔案
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:AppTheme"> <Style x:Key="style1" TargetType="Button"> <Setter Property="Width" Value="250"></Setter> <Setter Property="Height" Value="50"></Setter> <Setter Property="Foreground" Value="BurlyWood"></Setter> </Style></ResourceDictionary>
樣式檔案建立好之後,我們只需要在引用一下就可以使用了,我們可以在app.xaml檔案中引用或者在普通頁面引用,在APP.xaml引用是全域的,在普通頁面引用只能作用於當前的頁面,引用方式如下
在app.xaml中引用
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="buttonStyle.xaml"></ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
在頁面引用
<Page.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ButtonStyle.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Page.Resources>
windows phone中的樣式支援繼承,這樣在使用樣式的更加靈活,同時也可以減少代碼的冗餘。
<Style TargetType="Button" x:Key="pageStyle"> <Setter Property="Width" Value="200"></Setter> <Setter Property="Height" Value="30"> </Setter> <Setter Property="Foreground" Value="Green"></Setter> </Style> <!--樣式繼承--> <Style TargetType="TextBlock" BasedOn="{StaticResource pageStyle}" x:Key="textBlockStyle"> <Setter Property="TextWrapping" Value="Wrap"></Setter> </Style>
windows phone8.1樣式