WPF基础入门
Class8-资源基础
前言:方便各种资源的集中管理和动态效果
静态引用:初始化的时候确定样式,后续不发生改变
动态引用:样式随着引用的内容一起改变
1、新建资源字典.xaml
,创建一个边框颜色资源MyBrush
和一个button的style
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="DefaultButtonStyle" TargetType="Button">
<Setter Property="Foreground" Value="Red"></Setter>
<Setter Property="FontSize" Value="15"></Setter>
</Style>
<SolidColorBrush x:Key="MyBrush" Color="Yellow"/>
</ResourceDictionary>
2、在App.xaml
中引入资源字典
<Application.Resources>
<!--引入资源字典-->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/ButtonStyle.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
3、新建一个页面.xaml
<Window x:Class="WPF_Learn.Class_10_资源基础"
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:WPF_Learn"
mc:Ignorable="d"
Title="Class_10_资源基础" Height="450" Width="800">
<!--在App.xaml里面引入资源字典-->
<Grid>
<StackPanel>
<Button Content="点击我触发Test_Click" Click="Test_Click" Style="{StaticResource DefaultButtonStyle}"></Button>
<Button Content="静态引用,不会发生改变" Margin="0,5,0,5" BorderBrush="{StaticResource MyBrush}"></Button>
<Button Content="动态引用,点击按钮MyBrush改变后样式跟着改变" BorderBrush="{DynamicResource MyBrush}"></Button>
</StackPanel>
</Grid>
</Window>
private void Test_Click(object sender, RoutedEventArgs e)
{
// 资源的动态改变 静态引用在初始化的时候固定
this.Resources["MyBrush"] = new SolidColorBrush(Colors.Blue);
//寻找资源字典
//var solidColor = App.Current.FindResource("SolidColor");
//var style = App.Current.FindResource("DefaultButtonStyle");
}