2012-05-22 50 views
0

我在使用WPF在.NET中开发Windows应用程序。 那么,我们如何在运行时实现动态主题。我已经搜查了很多关于这个,但 我不能理解这件事。 如果我在app.xaml中添加下面的行,那么它会显示错误,因为我们如何直接添加事物行。虽然没有名称为“ExpressionDark”的文件。WPF中的动态主题

<ResourceDictionary Source="Themes/ExpressionDark.xaml"/> 
***or*** 
<ResourceDictionary Source="ExpressionDark.xaml"/> 

在此先感谢 :)

回答

0

假设由DynamicThemes,你的意思是把主题在运行这是将资源字典加载的最好方式,它将完整的控制风格加载到主应用程序或任何控件的资源中。

public static ResourceDictionary GetThemeResourceDictionary(Uri theme) 
    { 
     if (theme != null) 
     { 
      return Application.LoadComponent(theme) as ResourceDictionary; 
     } 
     return null; 
    } 

    public static void ApplyTheme(this ContentControl control /* Change this to Application to use this function at app level */, string theme) 
    { 
     ResourceDictionary dictionary = GetThemeResourceDictionary(theme); 

     if (dictionary != null) 
     { 
      // Be careful here, you'll need to implement some logic to prevent errors. 
      control.Resources.MergedDictionaries.Clear(); 
      control.Resources.MergedDictionaries.Add(dictionary); 
      // For app level 
      // app.Resources.MergedDictionaries.Clear(); 
      // app.Resources.MergedDictionaries.Add(dictionary); 

     } 
    } 
0

可以合并主题的App.xaml像这样:

<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="defaulttheme.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

的defaulttheme.xaml文件必须在你的项目的根。如果你想建立自己的主题日项目可以合并资源这样的:

<ResourceDictionary Source="/MyThemeProject;component/defaulttheme.xaml" />  

这里defaulthteme.xaml也必须在MyThemeProject根,不要忘记加上从该项目中添加引用你的主要项目。

要构建一个结构,您可以根据需要添加文件夹。

<ResourceDictionary Source="/MyThemeProject;component/Folder1/Folder2/defaulttheme.xaml" /> 

要切换主题,先清除MergedDictionaries然后添加新的主题

NewTheme = new Uri(@"/MyThemeProject;component/folder1/Folder2/bluetheme.xaml", UriKind.Relative); 

Application.Current.Resources.MergedDictionaries.Clear(); 
Application.Current.Resources.MergedDictionaries.Add(NewTheme); 

问候

flusser