WPF通过DynamicResource的用法

1.先在资源类库中编写:style.xaml,如下:

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
 
  <!-- Background Style -->
  <Style x:Key="styleBackground">
    <Setter Property="Control.Background">
      <Setter.Value>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.5">
          <GradientStop Color="LightSkyBlue" Offset="0" />
          <GradientStop Color="WhiteSmoke" Offset="0.5" />
          <GradientStop Color="LightSkyBlue" Offset="1" />
        </LinearGradientBrush>
      </Setter.Value>
    </Setter>
  </Style>
 
  <!-- Banner Style -->
  <Style x:Key="styleBanner">
    <Setter Property="StackPanel.Background">
      <Setter.Value>
        <LinearGradientBrush StartPoint="0,0.25" EndPoint="1,0.5">
          <GradientStop Color="#CC0088DD" Offset="0.3" />
          <GradientStop Color="#3300FFFF" Offset="0.85" />
        </LinearGradientBrush>
      </Setter.Value>
    </Setter>
    <Setter Property="TextBlock.Foreground" Value="Yellow" />
    <Setter Property="TextBlock.FontFamily" Value="Comic Sans MS" />
  </Style>
</ResourceDictionary>
 
2.在App.xaml类中,声明引用类型,
 <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/Resource;component/Styles/Style.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
 </Application.Resources>
 
3.在window、UserControl当中,直接使用动态资源,如下:
<Window  x:Class="SkinnableApp.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
 
  SizeToContent="Height"
  ResizeMode="NoResize"
  Width="680"
  WindowStartupLocation="CenterScreen"
  WindowStyle="ToolWindow">
  <Grid x:Name="Root" Style="{DynamicResource styleBackground}">
    <!-- BANNER -->
    <Grid Height="70" Style="{DynamicResource styleBanner}" >
      <TextBlock FontSize="26" Padding="10,0,10,0" Text="Insurance Agent Management System" VerticalAlignment="Center"/>
    </Grid>
</Window>
原文地址:https://www.cnblogs.com/wlming/p/10070635.html