从代码中,如何在存储在附加 属性 中的 object 上创建到 属性 的绑定?

From code, how can you create a binding to a property on an object stored in an attached property?

我们有一个继承附加 属性,它存储一个 object。在可视化树的更下方,我们希望通过代码绑定到 object 上的 属性。

通常我们像这样构造绑定的路径部分...

var someBinding = new Binding()
{
    Path = new PropertyPath(AttachedPropertyOwner.SomeAttachedProperty),
    RelativeSource = new RelativeSource(RelativeSourceMode.Self)
}; 

可以,但是我们现在想要 object 的 属性 存储在 SomeAttachedProperty 中。我认为我们应该使用字符串表示形式?

另外,在研究这个的时候,我在 MSDN 上发现了这个:Property Path Syntax

相关部分在'PropertyPathInCode'

标题下

If you construct a PropertyPath from a DependencyProperty, that PropertyPath is not usable as a Binding.Path, it is only usable for animation targeting. The Path value for the constructed PropertyPath from a DependencyProperty is the string value (0), which is a sentinel value used by the binding engine for an invalid path.

...这对我来说没有意义,因为它似乎工作正常。我错过了什么吗?我们所有的代码绑定都做错了吗?

更新

阅读 MSDN 文档评论(我错过了 Silverlight,但我认为在这种情况下不重要),它说你不能使用依赖项 属性。但是,它说你 can 使用 Dependency属性 identifier,标识符是什么从 Register 方法返回。

换句话说,我认为他们所说的是我们正在做的事情是有效的...

var someBinding = new Binding()
{
    Path = new PropertyPath(CarClass.WheelCountProperty)
}; 

...但这不是。

var someBinding = new Binding()
{
    Path = new PropertyPath(MyCarInstance.WheelCount)
}; 

似乎证实了这一点,在幕后,Reflector 表明它实际上只是在这样做...

public PropertyPath(object value)
: this("(0)", new [] { value })
{
    ....
}

...所以我认为那次恐慌是一个转移注意力的问题。

我认为这也意味着我可以像这样做我想做的事...

Path = new PropertyPath("(0).(1)",
    SomeClass.SomeAttachedProperty,
    SomeOtherClass.SomeOtherAttachedProperty)

...从存储在第一个附加 属性 中的 object 中获取第二个附加 属性 的值。

我刚刚证实了我之前的怀疑是正确的。这是绑定到附加 属性 存储在另一个附加 属性...

中的值所需要做的所有事情
Path = new PropertyPath("(0).(1)",
    SomeClass.SomeAttachedProperty,
    SomeOtherClass.SomeOtherAttachedProperty)

如更新中所述,对于简单属性,这也是有效的。

Path = new PropertyPath(SomeClass.SomeAttachedProperty)

...本质上等同于此...

Path = new PropertyPath("(0)",
    SomeClass.SomeAttachedProperty)