Set custom MarkupExtension from code

懵懂的女人 提交于 2019-12-01 04:37:02

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.

Fil

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!