XAML - MergedDictionaries throwing XmlParseException "item has already been added." What for?

I have the following, very easy to reproduce problem: I am creating a xaml application that uses resources from another file. To do this, create a MergedDictionaries tag to combine local and global resources, for example:

<Window> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="path.to.xaml.file"/> <ResourceDictionary> <Style TargetType="{x:Type Border}" x:Key="TypeBlock"> </Style> <Style TargetType="{x:Type Border}" x:Key="SetBlock"> </Style> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> .... </Window> 

This small piece of code will crash if you run it:

 Item has already been added. Key in dictionary: 'System.Windows.Controls.Border' Key being added: 'System.Windows.Controls.Border' 

If we remove the MergedDictionaries tag, the code will work as expected:

 <Window> <Window.Resources> <Style TargetType="{x:Type Border}" x:Key="TypeBlock"> </Style> <Style TargetType="{x:Type Border}" x:Key="SetBlock"> </Style> </Window.Resources> </Window> 

I do not understand why it throws an exception when we use Merged Resources. Of course, the fix is ​​simple enough for this (move resources to a lower level). It would be nice to know if this is a "normal" behavior ...

+6
styles wpf xaml resourcedictionary
source share
1 answer

If your resources are not in a separate file, they should not be part of merged dictionaries. Push them like this:

 <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="path.to.xaml.file"/> </ResourceDictionary.MergedDictionaries> <Style TargetType="{x:Type Border}" x:Key="TypeBlock"> </Style> <Style TargetType="{x:Type Border}" x:Key="SetBlock"> </Style> </ResourceDictionary> </Window.Resources> 

However, the error message is a little misleading and may be the result of an error in the XAML compiler.

+10
source share

All Articles