Application-level dynamic resources are not dynamic when placed in ElementHost

I host a WPF UserControl in a WinForms container. Now I want a UserControl theme / skin. To do this, I have several resource dictionaries that define “skins”. When my application starts, I create a "new System.Windows.Application ()" so that Application.Current exists. To change the theme, the old skin is deleted, and the new skin is merged into the application-level resource dictionary at run time. However, this does not change any of the diagonal related resources in UserControl. I tried this in a direct WPF application and everything worked out just fine. Am I missing something, or is it even impossible? By the way, if I add a skin to the application resources before UserControl is initialized, it will work, but after that I cannot change the skin.

To reinstall this in the easiest way:

Create a new WinForms application. Add the UserControl to the WPC application. It is quite simple:

<UserControl ...>
   <Grid>
      <Button
         Background="{DynamicResource ButtonBG}"/>
   </Grid>
</UserControl>

Create two ResourceDictionaries, White.xaml and Black.xaml (or something else) that have SolidColorBrush with the key ButtonBG with the appropriate color. In Form1.cs, add two buttons and an ElementHost element. Set the ElementHost child to the instance of the newly created UserControl. Connect the buttons to events that change the skin:

private void White_Click(object sender, EventArgs e)
{
   Application.Current.Resources.MergedDictionaries[0] = 
      (ResourceDictionary)Application.LoadComponent(
         new Uri(@"\WpfThemes;component\White.xaml", UriKind.Relative)));
}

private void Black_Click(object sender, EventArgs e)
{
   Application.Current.Resources.MergedDictionaries[0] = 
      (ResourceDictionary)Application.LoadComponent(
         new Uri(@"\WpfThemes;component\Black.xaml", UriKind.Relative)));
}

In Program.cs, make sure Application.Current exists and sets the initial skin:

[STAThread]
static void Main()
{
   new System.Windows.Application();

   Application.Current.Resources.MergedDictionaries[0] =
      (ResourceDictionary)Application.LoadComponent(
         new Uri(@"\WpfThemes;component\White.xaml", UriKind.Relative)));

   ...
}

Now that the White button is pressed, I expect the button in UserControl to turn white, and when I click the Black button, I expect the button to turn black. However, this does not happen.

Does anyone know why? Is there a solution?

: : , DynamicResources , .

, Dusty

+5
2

, WPF.

, Reflector, , Application (, , , , , ), , Windows DynamicResources. , WPF, ElementHost, . , .

, ElementHost , skin ResourceDictionary. , .

+6

. , , , .

, - (- > ) elementhost, .

-1

All Articles