MahApps.Metro的MVVM模式解析(二) 主題功能

tiankong007發表於2024-05-27

MahApps.Metro的MVVM模式解析(二) 主題功能
MahApps.Metro是一個開源的WPF框架,旨在為WPF應用程式提供現代和漂亮的使用者介面。
在MahApps.Metro中提供了切換主題的功能。經過多日的篩選和分析,在本文來理清它的脈絡。
1 主題功能演示
主題列表:

白天主題效果:

夜晚主題效果:

2軟體架構

3 分模組展示程式碼
View
頁面中主題列表程式碼如下。這是使用Menu 和MenuItem 來實現了選單效果
<Menu Grid.Row="0" Margin="5" HorizontalAlignment="Left" VerticalAlignment="Stretch"> <MenuItem Header="Theme" ItemContainerStyle="{StaticResource AppThemeMenuItemStyle}" ItemsSource="{Binding AppThemes, Mode=OneWay}" /> </Menu>
重要程式碼有兩處:
1 “ItemContainerStyle="{StaticResource AppThemeMenuItemStyle}"”
這裡透過樣式技術,實現了選單的點選後切換主題的功能
2 “ ItemsSource="{Binding AppThemes, Mode=OneWay}" ”
這裡透過與viewmodel的繫結實現了顯示主題列表的功能
擴充:wpf的樣式:
樣式(Style)是一種將一組屬性值應用到多個元素的便捷方法。
在這個專案中名為“AppThemeMenuItemStyle”的樣式程式碼如下:
<Style x:Key="AppThemeMenuItemStyle" BasedOn="{StaticResource MahApps.Styles.MenuItem}" TargetType="{x:Type MenuItem}"> <Setter Property="Command" Value="{Binding ChangeAccentCommand}" /> <Setter Property="CommandParameter" Value="{Binding Name, Mode=OneWay}" /> <Setter Property="Header" Value="{Binding Name, Mode=OneWay}" /> <Setter Property="Icon" Value="{StaticResource AppThemeMenuIcon}" /> </Style>

“BasedOn”:樣式可以繼承。
“Command”、“CommandParameter”:在樣式裡繫結控制元件的事件。這裡是選單項的點選事件。
“Header”:將控制元件屬性繫結到動態資料來源
“Icon”:將控制元件屬性繫結到靜態資源。

ViewModel
作為資料來源,具體程式碼 如下:
public List<AppThemeMenuData> AppThemes { get; set; } public ViewModel_Mainwin(IDialogCoordinator dialogCoordinator) { // create metro theme color menu items for the demo this.AppThemes = ThemeManager.Current.Themes .GroupBy(x => x.BaseColorScheme) ... .ToList(); }
ViewModel_Mainwin類中,定義了公開的 AppThemes 屬性。它包含了一個主題列表。
Model
當然為了實現複雜功能,AppThemes使用了AppThemeMenuData類。如下:

`public class AppThemeMenuData
{
public string? Name { get; set; }

	public Brush? BorderColorBrush { get; set; }

	public Brush? ColorBrush { get; set; }

	public AccentColorMenuData()
	{
		this.ChangeAccentCommand = new SimpleCommand<string?>(o => true, this.DoChangeTheme);
	}

	public ICommand ChangeAccentCommand { get; }

	protected virtual void DoChangeTheme(string? name)
	{
		if (name is not null)
		{
			ThemeManager.Current.ChangeThemeColorScheme(Application.Current, name);
		}
	}
}`

三個屬性不用說。複雜的是ChangeAccentCommand 事件。一方面它被繫結到頁面的點選事件上。另一方面,在建構函式里它被賦予一個匿名函式。透過呼叫DoChangeTheme函式來實現切換主題。

4 7附錄:
如何引用MahApps.Metro專案
如果將MahApps.Metro 新增到本地專案
方式1 :將原始碼下載到本地

將以下路徑的專案新增到當前解決方案。
“****\MahApps.Metro-develop\src\MahApps.Metro”
然後在主專案“的依賴項”選單上右鍵,選擇“新增專案引用”

在解決方案類別中選中MahApps.Metro專案並確定。

專案還使用了其他來源的圖表和樣式庫。可以透過NuGet工具引用

現在程式中有了它們的引用。可以開始編譯了

控制元件外外觀演示圖

相關文章