I'm working on conditionally loading a ResourceDictionary basing on which theme is currently selected. Say, that I have the following:
[Theme-Dark.xaml]
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- Colors --> <Color x:Key="Dark1Color">#1b2936</Color> <!-- ... --> <!-- Brushes --> <SolidColorBrush x:Key="TextboxNormalBackgroundBrush" Color="{StaticResource Dark1Color}" /> <!-- ... --> </ResourceDictionary> [Styles.xaml]
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- Styles --> <Style TargetType="TextBox"> <Setter Property="Background" Value="{StaticResource TextboxNormalBackgroundBrush}" /> </Style> </ResourceDictionary> If I add Theme-Dark.xaml to Styles.xaml's MergedDictionaries directly in xaml, everything works properly (so this is not a case of typos etc.). However, I would like to be able to load theme file with colors conditionally, basing on current application's theme. So I wrote the following code:
ResourceDictionary themeDictionary = new ResourceDictionary(); themeDictionary.Source = new Uri("/MyApp;component/Wpf/Theme-Dark.xaml", UriKind.RelativeOrAbsolute); ResourceDictionary styleDictionary = new ResourceDictionary(); styleDictionary.Source = new Uri("/MyApp;component/Wpf/Styles.xaml", UriKind.RelativeOrAbsolute); styleDictionary.MergedDictionaries.Add(themeDictionary); _content.Resources.MergedDictionaries.Add(styleDictionary); ehWpfContent.Child = _content; Upon opening the form containing ElementHost, which contains the control I want to style, I'm getting an exception:
System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception.' Line number '10' and line position '55'. ---> System.Exception: Cannot find resource named 'TextboxNormalBackgroundBrush'. Resource names are case sensitive. at System.Windows.StaticResourceExtension.ProvideValueInternal(IServiceProvider serviceProvider, Boolean allowDeferredReference) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider) How can I properly add ResourceDictionary to MergedDictionaries, so that those resources will be recognized?