MainWindow.xaml
<Window x:Class="WpfResource.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="brush" Color="Red" />
</Window.Resources>
<Grid>
<Grid.Resources>
<SolidColorBrush x:Key="lblBgColor" Color="Blue"/>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Name="lbl" Margin="71,44,77,0" Background="{StaticResource lblBgColor}" Height="49" Grid.Row="0"/>
<Button x:Name="btn" Content="Click Me" Click="Button_Click" Background="{DynamicResource brush}" Height="100" Width="100" Grid.Row="1" />
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfResource
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// this.btn.SetResourceReference(BackgroundProperty, "brush");
}
}
}
Output:
Related github is below:
https://github.com/LeoMingGit/WPF_UI_Design/tree/master/WpfResource