使用StaticResource给控件定义公共的样式和属性来写界面XAML

一:效果图

使用StaticResource给控件定义公共的样式和属性来写界面XAML

二:定义公共的样式和属性

在MainPage.xaml中
<phone:PhoneApplicationPage.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Brown"/>
<Style TargetType="Button" x:Key="MyButtonBackground">
<Setter Property="Background" Value="Blue"/>
</Style>
</phone:PhoneApplicationPage.Resources>
在App.xaml中,下划线部分
 <!--应用程序资源-->
<Application.Resources>
<local:LocalizedStrings xmlns:local="clr-namespace:XAMLResources" x:Key="LocalizedStrings"/>
<Style x:Name="MyTitleText"
BasedOn="{StaticResource PhoneTextBlockBase}"
TargetType="TextBlock">
<Setter Property="FontFamily"
Value="Verdana"/>
<Setter Property="FontSize"
Value="64"/>
</Style>

</Application.Resources>
MainPage.xaml的全部代码
<phone:PhoneApplicationPage
x:Class="XAMLResources.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"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True"> <phone:PhoneApplicationPage.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Brown"/>
<Style TargetType="Button" x:Key="MyButtonBackground">
<Setter Property="Background" Value="Blue"/>
</Style>
</phone:PhoneApplicationPage.Resources> <!--LayoutRoot 是包含所有页面内容的根网格-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions> <!--TitlePanel 包含应用程序的名称和页标题-->
<StackPanel x:Name="TitlePanel" Grid.Row="" Margin="12,17,0,28">
<TextBlock Text="红马車" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock
Text="hongmaju"
Margin="9,-7,0,0" Style="{StaticResource MyTitleText}"/>--------------使用了App.xaml中定义公共样式
</StackPanel> <!--ContentPanel - 在此处放置其他内容-->
<StackPanel x:Name="ContentPanel" Grid.Row="" Margin="12,0,12,0">
<Button
Height=""
Width=""
Background="{ StaticResource MyBrush }" >
</Button>
<Button
Height=""
Width=""
Style="{StaticResource MyButtonBackground}">
</Button>
<ListBox
Height=""
Width=""
Background="{StaticResource MyBrush}"> </ListBox> </StackPanel>
</Grid> </phone:PhoneApplicationPage>

三:将定义的公共样式和属性直接使用在相应控件位置的快捷方式(如下图)

使用StaticResource给控件定义公共的样式和属性来写界面XAML

上一篇:[Leetcode] search in rotated sorted array ii 搜索旋转有序数组


下一篇:WPF自定义控件与样式(15)-终结篇