简体   繁体   中英

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. 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

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.

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