Search code examples
wpfresourcedictionary

Using same ResourceDictionary object in multiple controls


I have a scenario where I parse the XAML of the resource dictionary at runtime. Like following:

var parsedResourceDictionary = XamlReader.Parse(xaml) as ResourceDictionary;

This all happens inside a custom resource dictionary (derived from ResourceDictionary as base class). After parsing, I call

MergedDictionaries.Add(parsedResourceDictionary);

Since parsing the XAML takes quite some time I want to cache the parsers output and just call the add method on the MergedDictionary field. Now, my question is if it is possible to keep a reference to this parsedResourceDictionary and add it later.

thanks


Solution

  • I just made a small testing app where I created a ResourceDictionary from an embedded XAML:

    public partial class MainWindow : Window
    {
        public static ResourceDictionary CachedResourceDictionary;
    
        public MainWindow()
        {
            if (CachedResourceDictionary == null)
            {
                CachedResourceDictionary = new ResourceDictionary
                {
                    Source =
                        new Uri("/ResourceDictionaryCache;component/Dictionary1.xaml",
                                UriKind.RelativeOrAbsolute)
                };
            }
            Resources.MergedDictionaries.Add(CachedResourceDictionary);
    
            InitializeComponent();
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var toOpen = new MainWindow();
            toOpen.Show();
        }
    }
    

    In the Button_Click event I just created a new instance of the MainWindow which then