【问题标题】:Custom WPF Binding自定义 WPF 绑定
【发布时间】:2011-09-20 10:38:50
【问题描述】:

我有一个模拟绑定的自定义 MarkupExtension。它在普通作业中效果很好,但在样式设置器中使用时效果不佳,例如:

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

导致 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);
    }
}

有什么问题?!

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    你为什么不这样做

    return Value
    

    ProvideValue??内

    其他

    您只能绑定到DependencyProperty。在 MyExtension 类中为 Value 创建一个依赖属性!

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Object), typeof(MyContentControl), new UIPropertyMetadata());
    

    【讨论】:

      【解决方案2】:

      从文档看来,该对象必须是可冻结的(因此它们可以在各个相关方之间共享)

      http://msdn.microsoft.com/en-us/library/system.windows.setter.value.aspx

      “如果指定的值是 Freezable 对象,则支持对象内的数据绑定和动态资源。请参阅 Binding Markup Extension 和 DynamicResource Markup Extension。”

      【讨论】:

      • Binding 不是Freezable。因此,特别支持。
      【解决方案3】:

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

      也就是说,你可能会逃脱惩罚:

      public class MyBinding : Binding
      {
          private object value;
      
          public object Value
          {
              get { return this.value; }
              set
              {
                  this.value = value;
                  this.Source = value;
              }
          }
      }
      

      因为ProvideValue 无论如何都会返回Binding 实例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-03
        • 2011-12-14
        • 2013-03-15
        • 2019-05-05
        • 2011-07-27
        • 2013-01-20
        • 2017-02-07
        • 1970-01-01
        相关资源
        最近更新 更多