【问题标题】:Is it possible to create a property of type BindingBase?是否可以创建 BindingBase 类型的属性?
【发布时间】:2014-06-11 05:06:26
【问题描述】:

我有一个用户控件,我在其中添加了一个名为“ImageBinding”的 BindingBase 类型的依赖项属性,我的问题是如何在 Xaml 中初始化此属性? 例如,如果我有一个名为 Value 的 int 类型的依赖属性,在 xaml 中我会这样初始化它:

Value="1"

Value={Binding Age}

但是如果我的属性类型是 BindingBase 呢?

【问题讨论】:

  • 是的,有可能。例如GridViewColumn 具有DisplayMemberBinding 类型的BindingBase 属性,但它是普通属性(不是DependencyProperty)。但我不明白你的问题是什么。您在创建此类属性时遇到问题吗?
  • 你不应该真的需要扩展 BindingBase 类。也许如果您让我们知道您实际想要做什么,我们可以提出更好的解决方案。
  • 你只能有一个普通的 CLR 属性 - 即它不能是一个 DependencyProperty。否则框架将看到 Binding 并尝试应用 Binding 为 DP 提供值。
  • 感谢@AndrewS,我将 ImageBinding 更改为 CLR 属性,它可以工作!

标签: c# wpf xaml binding dependency-properties


【解决方案1】:

我按照 AndrewS 的建议将 ImageBinding 更改为 CLR 属性,它可以正常工作。

【讨论】:

    【解决方案2】:

    在我的例子中,我正在创建一个 AttachedProperty,所​​以这意味着普通的 CLR 属性是不可能的。

    诀窍是将 DependencyProperty 类型声明为 BindingExpressionBase 而不是 BindingBase。

    然后您可以从 BindingExpressionBase.ParentBindingBase 属性访问 BindingBase。

    public static class Example
    {
        public static BindingExpressionBase GetMyBinding(DependencyObject obj)
        {
            return (BindingExpressionBase)obj.GetValue(MyBindingProperty);
        }
        public static void SetMyBinding(DependencyObject obj, BindingExpressionBase value)
        {
            obj.SetValue(MyBindingProperty, value);
        }
    
        public static readonly DependencyProperty MyBindingProperty =
            DependencyProperty.RegisterAttached(
                name:               "MyBinding",
                propertyType:       typeof(BindingExpressionBase),
                ownerType:          typeof(Example),
                defaultMetadata:    new FrameworkPropertyMetadata(null));
    }
    
    DependencyObject obj = ...;
    BindingBase bb = Example.GetMyBinding(obj)?.ParentBindingBase;
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多