Search code examples
c#wpfxamlmarkup-extensionsbaml

WPF MarkupExtension to Determine Assembly in which XAML is Embedded


I have a WPF project (in .NET 4.0) with XAML resources embedded in as assembly as Pages. In the XAML, I need to have MarkupExtension that is declared in another assembly that has no specific knowledge of the assembly with the XAML.

Now, I need this MarkupExtension to be able to access the assembly in which the XAML is embedded. How is this possible?


Solution

  • After a bit of playing around, I worked it out:

    public override object ProvideValue( IServiceProvider serviceProvider )
    {
        var contextProvider = (IXamlSchemaContextProvider)serviceProvider.GetService( typeof( IXamlSchemaContextProvider ) );
        var type = contextProvider.SchemaContext.GetType().Assembly.GetType( "System.Windows.Baml2006.Baml2006SchemaContext" );
        var property = type.GetProperty( "LocalAssembly", BindingFlags.Instance | BindingFlags.NonPublic );
        var assembly = (Assembly)property.GetValue( contextProvider, null );
        ...
    }
    

    Hope that helps someone else.