样式(3)----修改主题颜色
楔子:做软件时,经常有这样的需求,这样配色不合适?或者像动态的修改样式?那问题来了:怎样修软件界面的主题、修改皮肤?
方法1:使用第三方控件,直接更换主题,panuon 有类似的应用;
方法2:使用DynamicResource 资源,在代码中修改样式,然后引用该样式的所有主题将会被改变;下面介绍简单应用:
步骤一:定义样式,用 DynamicResource 引用:
<Window x:Class="HandyControlDemo.MainWindow"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:HandyControlDemo"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><SolidColorBrush x:Key="TestBrush" Color="#FF0000" /></Window.Resources><Grid><StackPanel><Button Width="150" Background="{DynamicResource TestBrush}" Content= "{Binding ContenTest}" Click="Button_SttkeCkucj"></Button></StackPanel></Grid>
</Window>
步骤二:在代码中修改 "TestBrush" 的值:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
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;
using static HandyControlDemo.MainWindow;namespace HandyControlDemo
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : System.Windows.Window, INotifyPropertyChanged{private string _contenTest;public string ContenTest {get { return _contenTest; }set {_contenTest = value; this.RaisePropertyChanged();}}public event PropertyChangedEventHandler PropertyChanged;public void RaisePropertyChanged([CallerMemberName] string propertyName = ""){if (this.PropertyChanged != null){this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));}}public MainWindow(){InitializeComponent();this.DataContext = this;ContenTest = "修改 DynamicResource";}private void Button_SttkeCkucj(object sender, RoutedEventArgs e){this.Resources["TestBrush"] = new SolidColorBrush(Colors.Green);ContenTest = "修改成功";}}
}
效果如下:
修改后:
演示完成。