Search code examples
c#wpfresourcedictionaryclass-library

Change Resource file at runtime in different class library project in same solution in WPF


I have a solution with these projects:

1.Clinica (Type is Windows Application),(MainWindow.xaml is here)

2.Ferhad.Wpf.Core (Type is Class Library), (There are three files: Resources.xaml, OrangeResource.xaml, BlueResource.xaml)

The Resources.xaml looks like that:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/Ferhad.Wpf.Core;component/BlueResource.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Now, from MainWindow.xaml.cs I want to clear and add OrangeReource.xaml to Resources.xaml.

How can i do that: So far I have tried this:

string fileName = "pack://application:,,,/Ferhad.Wpf.Core;component/OrangeReSource.xaml";
if (System.IO.File.Exists(fileName))
{
    using (FileStream fs = new FileStream(fileName, FileMode.Open))
    {
        ResourceDictionary dic = (ResourceDictionary)XamlReader.Load(fs);

        string fileNameR = "pack://application:,,,/Ferhad.Wpf.Core;component/Resources.xaml";
        if (System.IO.File.Exists(fileNameR))
        {
            using (FileStream fsR = new FileStream(fileNameR, FileMode.Open))
            {
                ResourceDictionary dicR = (ResourceDictionary)XamlReader.Load(fsR);
                dicR.MergedDictionaries.Clear();
                dicR.MergedDictionaries.Add(dic);
            }
        }
    }
}

Thanks.


Solution

  • I have done the job like that:

      var rDictionary = new ResourceDictionary();
      rDictionary.Source = new Uri(string.Format("pack://application:,,,/Ferhad.Wpf.SystemStyles;component/OStyles.xaml"), UriKind.Absolute);
      this.Resources.MergedDictionaries.Add(rDictionary);