WPF在使用样式的时候一般都是 Style="{StaticResource styleKey}",这里只能填一个样式,那么如何引用多个样式呢?
方法一:使用BaseOn
注意:
1.BaseOn所引用的样式一定要写在引用者的前面才有效;
2.所引用的样式的TargetType不能与引用者的TargetType不一致,但如果两者所应用的控件类型就是不一致怎么办,可在所引用的样式写Property时标注控件类型,例如行3-7中标注的TextBlock.
1 <!--导航栏按钮文字 - 选中后样式--> 2 <Style x:Key="NavBtnPressedFontStyle"> 3 <Setter Property="TextBlock.HorizontalAlignment" Value="Center"/> 4 <Setter Property="TextBlock.VerticalAlignment" Value="Center"/> 5 <Setter Property="TextBlock.FontFamily" Value="Microsoft Yahei"/> 6 <Setter Property="TextBlock.FontSize" Value="26"/> 7 <Setter Property="TextBlock.Foreground" Value="#ffffff"/> 8 </Style> 9 <!--左导航栏按钮 - 选中后样式--> 10 <Style x:Key="LeftNavBtnPressedStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource NavBtnPressedFontStyle}"> 11 <Setter Property="Template"> 12 <Setter.Value> 13 <ControlTemplate TargetType="{x:Type Button}"> 14 <Grid> 15 <Path x:Name="path" Data="M450,100 L400,50 550,50 600,100 z" Stretch="Fill" StrokeThickness="0" > 16 <Path.Fill> 17 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> 18 <GradientStop Color="#7000f5ff" Offset="0"/> 19 <GradientStop Color="#6000f5ff" Offset="0.1"/> 20 <GradientStop Color="#5000f5ff" Offset="0.2"/> 21 <GradientStop Color="#4000f5ff" Offset="0.3"/> 22 <GradientStop Color="#3000f5ff" Offset="0.4"/> 23 <GradientStop Color="#3000f5ff" Offset="0.6"/> 24 <GradientStop Color="#4000f5ff" Offset="0.7"/> 25 <GradientStop Color="#5000f5ff" Offset="0.8"/> 26 <GradientStop Color="#6000f5ff" Offset="0.9"/> 27 <GradientStop Color="#7000f5ff" Offset="1"/> 28 </LinearGradientBrush> 29 </Path.Fill> 30 </Path> 31 <ContentPresenter x:Name="content" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" 32 SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> 33 </Grid> 34 <ControlTemplate.Triggers> 35 <Trigger Property="IsFocused" Value="True"/> 36 <Trigger Property="IsDefaulted" Value="True"/> 37 <Trigger Property="IsMouseOver" Value="True"/> 38 <Trigger Property="IsPressed" Value="True"/> 39 <Trigger Property="IsEnabled" Value="False"/> 40 </ControlTemplate.Triggers> 41 </ControlTemplate> 42 </Setter.Value> 43 </Setter> 44 </Style>
方法二:使用WpfMultiStyle
1.在Nuget搜索安装;
2.在xaml页面引用;
3.在控件中同时使用多个样式,写法类似于 HTML 中 class="class1 class2 class3",非常方便。