自定义WPF绑定 [英] Custom WPF Binding

查看:80
本文介绍了自定义WPF绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的MarkupExtension,可以模拟绑定.它在常规分配中效果很好,但在样式设置器"中使用时效果不佳,例如:

I have a custom MarkupExtension that simulates binding. It works well in normal assignments but not when used in Style Setters, for example:

<Setter Property="Content" Value="{local:MyExtension}" />

导致XamlParseException:

results in a XamlParseException:

A 'Binding' cannot be set on the 'Value' property of type 'Setter'.
A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

这是扩展程序的实现:

public class MyExtension : MarkupExtension
{
    public MyExtension()
    {
        Value = 123;
    }

    public object Value
    {
        get;
        set;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var binding = new Binding("Value")
        {
            Source = this,
        };
        return binding.ProvideValue(serviceProvider);
    }
}

出什么问题了?!

推荐答案

有点猜想,但这很可能是因为XAML编译器对 Binding 类具有特殊的内置支持,从而允许将其用于这种情况(和其他情况). Binding 类也是 MarkupExtension ,但不幸的是,它密封了 ProvideValue()的实现.

Kind of guessing, but it's likely because the XAML compiler has special built-in support for the Binding class, allowing its usage in this scenario (and others). The Binding class is also a MarkupExtension, but unfortunately it seals its implementation of ProvideValue().

也就是说,您可能会摆脱这种情况:

That said, you might just get away with this:

public class MyBinding : Binding
{
    private object value;

    public object Value
    {
        get { return this.value; }
        set
        {
            this.value = value;
            this.Source = value;
        }
    }
}

因为 ProvideValue 将始终返回 Binding 实例.

这篇关于自定义WPF绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆