0

I am parsing an external Xaml file at runtime using Xaml.Parse, but I am getting the following exception:

System.Windows.Markup.XamlParseException failed to create TargetType from local:DemoElement.

This is the external Xaml file (ExternalFile.xaml):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:StyleDemo">
    <Style TargetType="local:DemoElement">
        <Style.Resources>
            <!--<Style TargetType="Button">-->
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <Trigger Property="Name" Value="Btn1">
                        <Setter Property="Background" Value="Green"/>
                        <Setter Property="Margin" Value="100, 100, 0, 0"/>
                        <Setter Property="VerticalAlignment" Value="Top"/>
                        <Setter Property="HorizontalAlignment" Value="Left"/>
                        <Setter Property="Width" Value="600"/>
                        <Setter Property="Height" Value="400"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Style.Resources>
    </Style>
</ResourceDictionary>

This is the runtime code to load the Xaml with XamlReader.Parse

string aspectRatio = File.ReadAllText("Data/Customization/AspectRatio/ExternalFile.xaml");
ResourceDictionary dictionaryAspectRatio = (ResourceDictionary)XamlReader.Parse(aspectRatio);
Application.Current.Resources.MergedDictionaries.Add(dictionaryAspectRatio);

The TargetType (inside the Xaml file) is a reference to a custom user control, so I need to add local: to access the namespace.

Maybe that's the problem? Is there a way to fix this?

Thanks.

Andrea
  • 125
  • 1
  • 1
  • 7
  • Does this answer your question? [How do XamlReader.Read or XamlReader.Parse instantiate types in order to build the wpf tree?](https://stackoverflow.com/questions/28639563/how-do-xamlreader-read-or-xamlreader-parse-instantiate-types-in-order-to-build-t) – Klaus Gütter Jun 29 '23 at 10:29
  • I tried it but it returns null: var xtype = context.GetXamlType(new XamlTypeName("clr-namespace:StyleDemo", "DemoElement")); – Andrea Jun 29 '23 at 13:13

0 Answers0