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开发者_StackOverflow中文版. 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.
I think there is no code-equivalent, the services are only available via XAML. From MSDN:
MarkupExtension has only one virtual method, ProvideValue. The input serviceProvider parameter is how the services are communicated to implementations when the markup extension is called by a XAML processor.
What about this as an alternative, it is generated in code but not necessarily as elegant as XAML:
var markup = new CustomMarkup();
markup.ProvideValue(new Target(textBox, TextBox.TextProperty));
The implementation for Target is simply:
public struct Target : IServiceProvider, IProvideValueTarget
{
private readonly DependencyObject _targetObject;
private readonly DependencyProperty _targetProperty;
public Target(DependencyObject targetObject, DependencyProperty targetProperty)
{
_targetObject = targetObject;
_targetProperty = targetProperty;
}
public object GetService(Type serviceType)
{
if (serviceType == typeof(IProvideValueTarget))
return this;
return null;
}
object IProvideValueTarget.TargetObject { get { return _targetObject; } }
object IProvideValueTarget.TargetProperty { get { return _targetProperty; } }
}
The only thing that remains is the ability to get a reference back to 'CustomMarkup' from the XAML object model. With the above you need to hang-on to a reference to it.
If your markup extension is fairly simple and creates a binding and returns the result from ProvideValue() then you can add a simple helper method:
public class CommandExtension : MarkupExtension
{
public CommandExtension(string name)
{
this.Name = name;
}
public string Name { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
return GetBinding(this.Name).ProvideValue(serviceProvider);
}
static Binding GetBinding(string name)
{
return new Binding("Commands[" + name + "]") { Mode = BindingMode.OneWay };
}
public static void SetBinding(DependencyObject target, DependencyProperty dp, string commandName)
{
BindingOperations.SetBinding(target, dp, GetBinding(commandName));
}
}
And then in code, you can just call CommandExtension.SetBinding() instead of BindingOperations.SetBinding().
Obviously, if you are doing anything more complex than this then this solution may not be appropriate.
This Silverlight TV show might shed some light on this issue. I recall them showing some code samples that might be helpful.
As H.B. pointed out, a MarkupExtension
is only intended to be used within XAML.
What makes Binding
unique is that it actually derives from MarkupExtension
which is what makes it possible to use the extension syntax {Binding ...}
or the full markup <Binding>...</Binding>
and use it in code.
However, you can always try creating an intermediary object (something akin to BindingOperations
) that knows how to use your custom markup extension and apply it to a target DependencyObject
.
To do this, I believe you would need to make use of the XamlSetMarkupExtensionAttribute
(for .NET 4) or the IReceiveMarkupExtension
interface (for .NET 3.x). I am not entirely sure how to make use of the attribute and/or interface, but it might point you in the right direction.
How do I set a custom MarkupExtension from code?
If you can modify it, then simply extract the logic into separate SomeMethod
which can be called alone and/or from ProvideValue
.
Then instead of
textBox.Text = customExtension.ProvideValue(??);
you just call it
customExtension.SomeMethod(textBox, TextBox.TextProperty);
Often we are creating custom property extensions (used like this in xaml):
<TextBox Text="{local:SomeExtension ...}" />
This can be written like this:
public class SomeExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
var provider = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
var target = provider.TargetObject as DependencyObject;
var property = provider.TargetProperty as DependencyProperty;
// defer execution if target is data template
if (target == null)
return this;
return SomeMethod(target, property);
}
public object SomeMethod(DependencyObject target, DependencyProperty property)
{
... // do something
}
}
Since I realized there is sometimes a necessity to use markup extensions from code I am always trying to write them in such a way.
精彩评论