WPF 样式
程序员文章站
2022-07-13 22:55:07
...
WPF样式
一.简单设置样式
<Window x:Class="WPF0303.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<SolidColorBrush x:Key="myStyle" Color="Green"></SolidColorBrush>
</Window.Resources>
<Grid>
<StackPanel>
<Button Name="btn_One" Width="100" Height="50" Content="ONE" Background="{StaticResource myStyle}"></Button>
<Button Name="btn_Two" Width="100" Height="50" Content="TWO" Background="{DynamicResource myStyle}" Click="btn_Two_Click"></Button>
</StackPanel>
</Grid>
</Window>
按键TWO的触发事件代码:
private void btn_Two_Click(object sender, RoutedEventArgs e)
{
this.Resources["myStyle"] = new SolidColorBrush(Colors.Red);
}
二.新建一个资源字典,在里面添加样式
eg:新建资源字典为:TestDictionary,代码如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="testStyle1" TargetType="{x:Type Button}">
<Setter Property="Background" Value="Pink"></Setter>
<Setter Property="FontSize" Value="28"></Setter>
</Style>
<Style x:Key="testStyle2" TargetType="{x:Type Button}" BasedOn="{StaticResource testStyle1}">
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
<SolidColorBrush x:Key="testStyle3" Color="Gold"></SolidColorBrush>
</ResourceDictionary>
在App.xaml中把新建的资源字典引用进来:
<Application x:Class="WPF0303.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="TestDictionary.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
然后就可以在窗体中使用:
<Grid>
<StackPanel>
<Button Name="btn_One" Width="100" Height="50" Content="ONE" Style="{StaticResource testStyle1}"></Button>
</StackPanel>
</Grid>
推荐阅读