WPF(多样式)
XAML能不能像HTML一样可以对元素应用多个样式呢???默认的情况下是不可以的,下面将讲述两种通过其他方法实现同时应用多个样式的例子。
1.BasedOn
通过继承相当于拥有两种样式。
<Window x:Class="WpfAppLearn2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppLearn2"
xmlns:ms="clr-namespace:WpfMultiStyle;assembly=WpfMultiStyle"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="319" Background="#FFD4D2D2" WindowStartupLocation="CenterScreen">
<Canvas HorizontalAlignment="Left" VerticalAlignment="Top">
<Canvas.Resources>
<Style x:Key="tbStyle1" TargetType="TextBox">
<Setter Property="Background" Value="Maroon"/>
<Style.Triggers>
<Trigger Property="Text" Value="123">
<Setter Property="Foreground" Value="Chocolate"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="tbStyle2" TargetType="TextBox" BasedOn="{StaticResource tbStyle1}">
<Setter Property="Background" Value="Gold"/>
<Style.Triggers>
<Trigger Property="Text" Value="123">
<Setter Property="Foreground" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
</Canvas.Resources>
<TextBox Height="23" Style="{StaticResource tbStyle2}" Text="C#" Width="120" Canvas.Left="65" Canvas.Top="235"/>
<Button Content="Button" Width="75"/>
</Canvas>
</Window>
2. WpfMultiStyle
NuGet搜索安装WpfMultiStyle:
<Window x:Class="WpfAppLearn2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppLearn2"
xmlns:ms="clr-namespace:WpfMultiStyle;assembly=WpfMultiStyle"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="319" Background="#FFD4D2D2" WindowStartupLocation="CenterScreen">
<Canvas HorizontalAlignment="Left" VerticalAlignment="Top">
<Canvas.Resources>
<Style x:Key="tbStyle1" TargetType="TextBox">
<Setter Property="Background" Value="Maroon"/>
<Style.Triggers>
<Trigger Property="Text" Value="123">
<Setter Property="Foreground" Value="Chocolate"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="tbStyle2" TargetType="TextBox">
<Setter Property="Background" Value="Gold"/>
<Style.Triggers>
<Trigger Property="Text" Value="123">
<Setter Property="Foreground" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
</Canvas.Resources>
<TextBox Height="23" Style="{ms:MultiStyle tbStyle2 tbStyle1 }" Text="C#" Width="120" Canvas.Left="65" Canvas.Top="235"/>
<Button Content="Button" Width="75"/>
</Canvas>
</Window>
引用名称空间:xmlns:ms="clr-namespace:WpfMultiStyle;assembly=WpfMultiStyle"
就可以应用多样式了:TextBox Height="23" Style="{ms:MultiStyle tbStyle2 tbStyle1 }"
多样式应用相当于依次应用样式,所以同样的属性设置,最后一次有效。