DMX David Cardinal
DMX David Cardinal

Reputation: 659

How to define the type of a MarkupExtension provided value?

I have an issue in xaml where a custom MarkupExtension's ProvideValue returns a string, but the xaml "compilation" doesn't know that and gives the following error: A key for a dictionary cannot be of type 'MyNamespace.MyExtension'. Only String, TypeExtension, and StaticExtension are supported. That error is unfortunate, since I know that the value provided will, in fact, be a string, which is an accepted type, as per the error message. Here is an example that reproduces the error:

Extension code:

[MarkupExtensionReturnType(typeof(String))]
public class MyExtension : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return "Hello World!";
    }
}

Usage:

<sys:Double x:Key="{my:MyExtension}">99</sys:Double>

EDIT2: Simplified the question as I found after testing that it could be more specific

Upvotes: 0

Views: 356

Answers (1)

nalka
nalka

Reputation: 2380

To fix your problem, you can make MyExtension inherit from either StaticExtension or TypeExtension (both from System.Windows.Markup). This doesn't look really clean since MyExtension isn't related to TypeExtension or StaticExtension but that's the only way I know of to bypass the compile time check that makes sure resource keys are only of type String, TypeExtension or StaticExtension.

After inheriting from TypeExtension or StaticExtension there's nothing more to do than if you were inheriting directly from MarkupExtension (so you only have to override ProvideValue) with your current implementation.

Upvotes: 1

Related Questions