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
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 do I set a custom
MarkupExtension
from code? Should I callProvideValue
and it that case, how do I get a hold of aIServiceProvider
?*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 that you should return the MarkupExtension
itself if the TargetObject
is a Setter
to allow it to reeavaluate once it is being applied to an actual FrameworkElement
and this makes sense.
- Markup Extension in Data Trigger
- Huge limitation of a MarkupExtension
- A base class for custom WPF binding markup extensions (in the comments)
However, that only works when the TargetProperty
is of type object
, otherwise the exception is back. If you look at the source code for BindingBase
you can see that it does exactly this but it appears the framework has some secret ingredient that makes it work.