How do you install custom MarkupExtension from code?
You can easily install if from Xaml. The same goes for Binding and DynamicResource .
<TextBox FontSize="{Binding MyFontSize}" Style="{DynamicResource MyStyle}" Text="{markup:CustomMarkup}"/>
Setting the same values ββwith the code behind requires a slightly different approach
Binding: Use textBox.SetBinding or BindingOperations.SetBinding
Binding binding = new Binding("MyFontSize"); BindingOperations.SetBinding(textBox, TextBox.FontSizeProperty, binding);
DynamicResource: Use SetResourceReference
textBox.SetResourceReference(TextBox.StyleProperty, "MyStyle");
CustomMarkup: How to install custom MarkupExtension from code? Should I call ProvideValue , in which case, how can I get IServiceProvider ? *
CustomMarkupExtension customExtension = new CustomMarkupExtension(); textBox.Text = customExtension.ProvideValue(??);
I found surprisingly little on this, can this be done?
HB answered the question. Just add some details here, why I wanted to do this. I tried to create a workaround for the following problem.
The problem is that you cannot get Binding and override ProvideValue , as it is sealed. You will need to do something like this: Base class for custom WPF markup extensions . But then the problem is that when you return Binding to Setter , you get an exception, but outside Style it works fine.
I read in several places that you should return MarkupExtension itself if TargetObject is a Setter so that it can reeavaluate as soon as it applies to the actual FrameworkElement , and that makes sense.
However, this only works when TargetProperty is of type object , otherwise an exception will be thrown. If you look at the source code for the BindingBase , you will see that it does just that, but it seems that there is some secret ingredient in the framework that makes it work.
Fredrik hedblad
source share