WPF實現主題更換的簡單DEMO
WPF實現主題更換的簡單DEMO
實現主題更換功能主要是三個知識點:
- 動態資源 ( DynamicResource )
- INotifyPropertyChanged 接口
- 界面元素與數據模型的綁定 (MVVM中的ViewModel)
Demo 代碼地址:GITHUB
下面開門見山,直奔主題
一、準備主題資源
在項目 (怎麽建項目就不說了,百度上多得是) 下面新建一個文件夾 Themes,主題資源都放在這裏面,這裏我就簡單實現了兩個主題 Light /Dark,主題只包含背景顏色一個屬性。
1. Themes
- Theme.Dark.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ModernUI.Example.Theme.Themes"> <Color x:Key="WindowBackgroundColor">#333</Color> </ResourceDictionary>
- Theme.Light.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ModernUI.Example.Theme.Themes"> <Color x:Key="WindowBackgroundColor">#ffffff</Color> </ResourceDictionary>
然後在程序的App.xaml中添加一個默認的主題
不同意義的資源最好分開到單獨的文件裏面,最後Merge到App.xaml裏面,這樣方便管理和搜索。
- App.xaml
<Application x:Class="ModernUI.Example.Theme.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:ModernUI.Example.Theme" StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Themes/Theme.Light.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
二、實現視圖模型 (ViewModel)
界面上我模仿 ModernUI ,使用ComboBox 控件來更換主題,所以這邊需要實現一個視圖模型用來被 ComboBox 綁定。
新建一個文件夾 Prensentation ,存放所有的數據模型類文件
1. NotifyPropertyChanged 類
NotifyPropertyChanged 類實現 INotifyPropertyChanged 接口,是所有視圖模型的基類,主要用於實現數據綁定功能。
abstract class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
這裏面用到了一個 [CallerMemberName] Attribute ,這個是.net 4.5裏面的新特性,可以實現形參的自動填充,以後在屬性中調用 OnPropertyChanged 方法就不用在輸入形參了,這樣更利於重構,不會因為更改屬性名稱後,忘記更改 OnPropertyChanged 的輸入參數而導致出現BUG。具體可以參考 C# in depth (第五版) 16.2 節 的內容
2. Displayable 類
Displayable 用來實現界面呈現的數據,ComboBox Item上顯示的字符串就是 DisplayName 這個屬性
class Displayable : NotifyPropertyChanged
{
private string _displayName { get; set; }
/// <summary>
/// name to display on ui
/// </summary>
public string DisplayName
{
get => _displayName;
set
{
if (_displayName != value)
{
_displayName = value;
OnPropertyChanged();
}
}
}
}
3. Link 類
Link 類繼承自 Displayable ,主要用於保存界面上顯示的主題名稱(DisplayName),以及主題資源的路徑(Source)
class Link : Displayable
{
private Uri _source = null;
/// <summary>
/// resource uri
/// </summary>
public Uri Source
{
get => _source;
set
{
_source = value;
OnPropertyChanged();
}
}
}
4. LinkCollection 類
LinkCollection 繼承自 ObservableCollection<Link>,被 ComboBox 的 ItemsSource 綁定,當集合內的元素發生變化時,ComboBox 的 Items 也會一起變化。
class LinkCollection : ObservableCollection<Link>
{
/// <summary>
/// Initializes a new instance of the <see cref="LinkCollection"/> class.
/// </summary>
public LinkCollection()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LinkCollection"/> class that contains specified links.
/// </summary>
/// <param name="links">The links that are copied to this collection.</param>
public LinkCollection(IEnumerable<Link> links)
{
if (links == null)
{
throw new ArgumentNullException("links");
}
foreach (var link in links)
{
Add(link);
}
}
}
5.ThemeManager 類
ThemeManager 類用於管理當前正在使用的主題資源,使用單例模式 (Singleton) 實現。
class ThemeManager : NotifyPropertyChanged
{
#region singletion
private static ThemeManager _current = null;
private static readonly object _lock = new object();
public static ThemeManager Current
{
get
{
if (_current == null)
{
lock (_lock)
{
if (_current == null)
{
_current = new ThemeManager();
}
}
}
return _current;
}
}
#endregion
/// <summary>
/// get current theme resource dictionary
/// </summary>
/// <returns></returns>
private ResourceDictionary GetThemeResourceDictionary()
{
return (from dictionary in Application.Current.Resources.MergedDictionaries
where dictionary.Contains("WindowBackgroundColor")
select dictionary).FirstOrDefault();
}
/// <summary>
/// get source uri of current theme resource
/// </summary>
/// <returns>resource uri</returns>
private Uri GetThemeSource()
{
var theme = GetThemeResourceDictionary();
if (theme == null)
return null;
return theme.Source;
}
/// <summary>
/// set the current theme source
/// </summary>
/// <param name="source"></param>
public void SetThemeSource(Uri source)
{
var oldTheme = GetThemeResourceDictionary();
var dictionaries = Application.Current.Resources.MergedDictionaries;
dictionaries.Add(new ResourceDictionary
{
Source = source
});
if (oldTheme != null)
{
dictionaries.Remove(oldTheme);
}
}
/// <summary>
/// current theme source
/// </summary>
public Uri ThemeSource
{
get => GetThemeSource();
set
{
if (value != null)
{
SetThemeSource(value);
OnPropertyChanged();
}
}
}
}
6. SettingsViewModel 類
SettingsViewModel 類用於綁定到 ComboBox 的 DataContext 屬性,構造器中會初始化 Themes 屬性,並將我們預先定義的主題資源添加進去。
ComboBox.SelectedItem -> SettingsViewModel.SelectedTheme
ComboBox.ItemsSource -> SettingsViewModel.Themes
class SettingsViewModel : NotifyPropertyChanged
{
public LinkCollection Themes { get; private set; }
private Link _selectedTheme = null;
public Link SelectedTheme
{
get => _selectedTheme;
set
{
if (value == null)
return;
if (_selectedTheme != value)
_selectedTheme = value;
ThemeManager.Current.ThemeSource = value.Source;
OnPropertyChanged();
}
}
public SettingsViewModel()
{
Themes = new LinkCollection()
{
new Link { DisplayName = "Light", Source = new Uri(@"Themes/Theme.Light.xaml" , UriKind.Relative) } ,
new Link { DisplayName = "Dark", Source = new Uri(@"Themes/Theme.Dark.xaml" , UriKind.Relative) }
};
SelectedTheme = Themes.FirstOrDefault(dcts => dcts.Source.Equals(ThemeManager.Current.ThemeSource));
}
}
三、實現視圖(View)
1.MainWindwo.xaml
主窗口使用 Border 控件來控制背景顏色,Border 的 Background.Color 指向到動態資源 WindowBackgroundColor ,這個 WindowBackgroundColor 就是我們在主題資源中定義好的 Color 的 Key,因為需要動態更換主題,所以需要用DynamicResource 實現。
Border 背景動畫比較簡單,就是更改 SolidColorBrush 的 Color 屬性。
ComboBox 控件綁定了三個屬性 :
- ItemsSource="{Binding Themes }" -> SettingsViewModel.Themes
- SelectedItem="{Binding SelectedTheme , Mode=TwoWay}" -> SettingsViewModel.SelectedTheme
- DisplayMemberPath="DisplayName" -> SettingsViewModel.SelectedTheme.DisplayName
<Window ...>
<Grid>
<Border x:Name="Border">
<Border.Background>
<SolidColorBrush x:Name="WindowBackground" Color="{DynamicResource WindowBackgroundColor}"/>
</Border.Background>
<Border.Resources>
<Storyboard x:Key="BorderBackcolorAnimation">
<ColorAnimation
Storyboard.TargetName="WindowBackground" Storyboard.TargetProperty="Color"
To="{DynamicResource WindowBackgroundColor}"
Duration="0:0:0.5" AutoReverse="False">
</ColorAnimation>
</Storyboard>
</Border.Resources>
<ComboBox x:Name="ThemeComboBox"
VerticalAlignment="Top" HorizontalAlignment="Left" Margin="30,10,0,0" Width="150"
DisplayMemberPath="DisplayName"
ItemsSource="{Binding Themes }"
SelectedItem="{Binding SelectedTheme , Mode=TwoWay}" >
</ComboBox>
</Border>
</Grid>
</Window>
2. MainWindow.cs
後臺代碼將 ComboBox.DataContext 引用到 SettingsViewModel ,實現數據綁定,同時監聽 ThemeManager.Current.PropertyChanged 事件,觸發背景動畫
public partial class MainWindow : Window
{
private Storyboard _backcolorStopyboard = null;
public MainWindow()
{
InitializeComponent();
ThemeComboBox.DataContext = new Presentation.SettingsViewModel();
Presentation.ThemeManager.Current.PropertyChanged += AppearanceManager_PropertyChanged;
}
private void AppearanceManager_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_backcolorStopyboard != null)
{
_backcolorStopyboard.Begin();
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (Border != null)
{
_backcolorStopyboard = Border.Resources["BorderBackcolorAnimation"] as Storyboard;
}
}
}
四、總結
關鍵點:
- 綁定 ComboBox(View層) 的 ItemsSource 和 SelectedItem 兩個屬性到 SettingsViewModel (ViewModel層)
- ComboBox 的 SelectedItem 被更改後,會觸發 ThemeManager 替換當前正在使用的主題資源(ThemeSource屬性)
- 視圖模型需要實現 INotifyPropertyChanged 接口來通知 WPF 框架屬性被更改
- 使用 DynamicResource 引用 會改變的 資源,實現主題更換。
另外寫的比較啰嗦,主要是給自己回過頭來復習看的。。。這年頭WPF也沒什麽市場了,估計也沒什麽人看吧 o(╥﹏╥)o
WPF實現主題更換的簡單DEMO