简体   繁体   中英

Custom MarkupExtension causes TypeInitializationException during design time only

I am working on a custom markup extension, whose role is simple:

To use the System.Activator on the extension constructor parameter (a type) and instantiate it.

 public class MyExtension : MarkupExtension
 {
    private readonly Type _myType;

    public MyExtension (Type param)
    {
        _myType= param;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return Activator.CreateInstance(_myType);
    }
 }

During Runtime, this extension acts as expected.

But during design time, an exception is thrown while activating the type.

I've drilled down to find the source, and caught the whale:

    try
    {
        return Activator.CreateInstance(_myType);
    }
    catch (TypeInitializationException ex)
    {

    }

So I looped over this:

 (ex.InnerException as ReflectionTypeLoadException).LoaderExceptions[i].Message);

And retrieved the following messages

Could not find Windows Runtime type 'Windows.ApplicationModel.Core.IFrameworkView'.

Could not find Windows Runtime type 'Windows.ApplicationModel.Core.IFrameworkViewSource'.

Since my code works fine during runtime, My only guess is that the VS (2013 update 2 on .NET 4.5.1)

Or the Xaml Designer are just looking in the wrong Assembly.

Any ideas on how to fix this, or any other takes on the issue, perhaps?

Thank you very much for taking the time.

I have researched this issue further and have come to the following conclusion:

The only solution for this problem is to differentiate between the return value at design time and the return value at runtime.

This is fairly easily done, and was implemented in a WPF framework I am developing.

See PerrypheralFramework

The relevant assembly is PerrypheralFramework.WPF, The relevant class is: PerrypheralFramework.WPF.MarkupExtensions.Base.DependencyObjectDependantExtensionBase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM