Adding a static ResourceDictionary to UserControls before XAML analysis

I have one WPF control that I want to use in my WinForms application (using ElementHost) in several places (=> several instances of this control).

In addition, I want all instances of my UserControl to share one instance of ResourceDictionary.

In WPF applications, I would achieve this by combining my ResourceDictionary in application resources.

However, I do not want to instantiate the WPF application in the WinForms application. Instead, I am looking for another way.

I found one solution, but I hope you know a better way that does not require any code:

public static class StaticRDProvider { static ResourceDictionary rd; static StaticRDProvider() { var uri = new Uri("WpfControls;Component/GlobalResourceDictionary.xaml", UriKind.Relative); rd = (ResourceDictionary) Application.LoadComponent(uri); } public static ResourceDictionary GetDictionary { get { return rd; } } } 

UserControl.xaml.cs:

  public partial class MyCustomUserControl : UserControl { public MyCustomUserControl() { Resources.MergedDictionaries.Add(StaticRDProvider.GetDictionary); InitializeComponent(); } } 

It works. But I prefer a solution that only works with XAML. In addition, I want to use StaticResources. Therefore, adding a static ResourceDictionary resource to MergedDictionaries Controls after the control is initialized is not an option.

I tried the following, but this throws the strange exception "stack is empty":

 <UserControl x:Class="WpfControls.MyCustomUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:WpfControls="clr-namespace:WpfControls" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <x:Static Member="WpfControls:StaticRDProvider.GetDictionary"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> <Grid> </Grid> 

Maybe someone knows a better approach.

Thanks TwinHabit

+4
source share
1 answer

Have you tried loading RD into your UserControl in the same way as with the Application class?

 <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="WpfControls;Component/GlobalResourceDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> 

That way, you simply specify the URI in your user control and avoid static members altogether.

BTW, be sure to use the correct URI syntax if RD is not in the same assembly as UserControl. For example: pack: // application: ,, / YourAssembly; component / Subfolder / YourResourceFile.xaml ( additional information about the package URI )

-1
source

All Articles