Alex Rivera | Logout

Set custom MarkupExtension from code

Asked 2011-09-20T18:15:41.127
9

How do you set a custom MarkupExtension from code?

You can easily set if from Xaml. The same goes for Binding and DynamicResource.

<TextBox FontSize="{Binding MyFontSize}"
         Style="{DynamicResource MyStyle}"
         Text="{markup:CustomMarkup}"/>

Setting the same values through code behind requires a little different approach

  1. Binding: Use textBox.SetBinding or BindingOperations.SetBinding

    Binding binding = new Binding("MyFontSize");
    BindingOperations.SetBinding(textBox, TextBox.FontSizeProperty, binding);
    
  2. DynamicResource: Use SetResourceReference

    textBox.SetResourceReference(TextBox.StyleProperty, "MyStyle");
    
  3. CustomMarkup: How do I set a custom MarkupExtension from code? Should I call ProvideValue and it that case, how do I get a hold of a IServiceProvider?*

    CustomMarkupExtension customExtension = new CustomMarkupExtension();
    textBox.Text = customExtension.ProvideValue(??);
    

I found surprisingly little on the subject so, can it be done?


H.B. has answered the question. Just adding some details here to why I wanted to do this. I tried to create a workaround for the following problem.

The problem is that you can't derive from Binding and override ProvideValue since it is sealed. You'll have to do something like this instead: A base class for custom WPF binding markup extensions. But then the problem is that when you return a Binding to a Setter you get an exception, but outside of the Style it works fine.

I've read in several places tha

Edit
Report

1 Answer

2

This Silverlight TV show might shed some light on this issue. I recall them showing some code samples that might be helpful.

answered 2011-09-20T19:24:57.177

Your Answer