2017-03-16 23 views
1

我是mahapps.metro主題中的新成員。當我使用ThemeManager它只工作一次,然後在第二次使用它引發空引用異常。例如首先我選擇藍色主題它的作品,但之後,我選擇綠色主題它不起作用,並提出一個空引用異常。 這裏是一個示例代碼:如何在代碼中使用ThemeManager behinde

ThemeManager.ChangeAppStyle(Application.Current, 
            ThemeManager.GetAccent("Blue"), 
            ThemeManager.GetAppTheme("BaseDark")); 
ThemeManager.ChangeAppStyle(Application.Current, 
            ThemeManager.GetAccent("Green"), 
            ThemeManager.GetAppTheme("BaseDark")); 

有什麼不好?

回答

0

這行應該在App.xaml代碼的後面或主窗口構造函數的這一點上工作。

using System.Windows; 
using MahApps.Metro; 

namespace MetroDemo 
{ 
    /// <summary> 
    /// Interaction logic for App.xaml 
    /// </summary> 
    public partial class App : Application 
    { 
     protected override void OnStartup(StartupEventArgs e) 
     { 
      base.OnStartup(e); 
      ThemeManager.ChangeAppStyle(Application.Current, 
             ThemeManager.GetAccent("Blue"), 
             ThemeManager.GetAppTheme("BaseDark")); 
      ThemeManager.ChangeAppStyle(Application.Current, 
             ThemeManager.GetAccent("Green"), 
             ThemeManager.GetAppTheme("BaseDark")); 
     } 
    } 
} 

確保您添加的必要的資源的App.xaml,因爲你想改變你的應用程序的資源!

<Application x:Class="MetroDemo.App" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      StartupUri="MainWindow.xaml"> 
    <Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
     <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! --> 
     <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" /> 
     <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" /> 
     <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" /> 
     <!-- Accent and AppTheme setting --> 
     <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" /> 
     <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
    </Application.Resources> 
</Application> 

希望這有助於。

相關問題