在我們前面介紹資源的時候,我們提到了樣式表,如果你之前是做Web開發的,你會發現Style有點類似于Web中的CSS。
控件級別樣式
我們可以在控件級別定義自己的樣式,控件級別的樣式是優先級最高的
<Window x:Class="Example_06.SelfControlStyle"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:Example_06"mc:Ignorable="d" Title="SelfControlStyle"?Height="450"?Width="800"><Grid><TextBlock Text="TextBlock"><TextBlock.Style><Style><Setter Property="TextBlock.Foreground" Value="Red"></Setter><Setter?Property="TextBlock.FontSize"?Value="100"></Setter></Style></TextBlock.Style></TextBlock></Grid>
</Window>
我們為控件定義了自己的樣式
父級控件級別樣式
<Window x:Class="Example_06.ParentControlStyle"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"mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"><StackPanel><StackPanel.Resources><Style TargetType="Button"><Setter Property="Background" Value="Green"></Setter><Setter Property="Foreground" Value="White"></Setter><Setter?Property="FontSize"??Value="40"></Setter></Style></StackPanel.Resources><Button>Button 1</Button><Button>Button 2</Button><Button Background="red">Button 3</Button></StackPanel>
</Window>
上面例子中我們在StackPanel中定義了樣式,會應用容器里面所有Button,當然你也可以在Button級別覆蓋父控件的樣式
Window窗體級別樣式
<Window x:Class="Example_06.WindowControlStyle"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:Example_06"mc:Ignorable="d" Title="WindowControlStyle" Height="450" Width="800"><Window.Resources><Style TargetType="Button"><Setter Property="Background" Value="Green"></Setter><Setter Property="Foreground" Value="White"></Setter><Setter?Property="FontSize"??Value="30"></Setter></Style></Window.Resources><StackPanel><Button>Button 1</Button><Button>Button 2</Button><Button Background="red">Button 3</Button></StackPanel>
</Window>
我們將樣式移到Window窗體級別,會將樣式應用到該窗體的所有Button
應用程序級別樣式
<Application x:Class="Example_06.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:Example_06"StartupUri="ParentControlStyle.xaml"><Application.Resources><Style TargetType="Button"><Setter Property="Background" Value="Green"></Setter><Setter Property="Foreground" Value="White"></Setter><Setter?Property="FontSize"??Value="20"></Setter></Style></Application.Resources>
</Application>
我們可以將樣式定義為應用程序級別樣式,樣式表的優先級子節點樣式可以覆蓋父節點的樣式,從下往上查找