Search code examples
c#wpftextblockmarkup-extensions

How to use markup extensions from C# code?


Assume I have SomeExtension MarkupExtension. Does anyone know how to assign it to a property from C# code?

That is for example in XAML I have:

<TextBlock Text="{l:Translate LocalizedByMarkupExtension}" />

I want to do the same using C# code.


Solution

  • In your example, your TranslateExtension would need to implement a constructor that takes a single parameter. So you'd just need to pass the value into the constructor like so:

    TranslateExtension ext = new TranslateExtension("LocalizedByMarkupExtension");
    

    The parameter may be converted using an associated TypeConverter or a special Xaml value converter. But if you are simply passing strings, then the above should work.

    Then you'd call ProvideValue method to get the result.