通过PlacementTarget绑定依赖属性失败-路径语法错误



没问题

我创建了一个依赖属性,它接受一个字符串值。我把它设置在TextBlock上,它工作了:

<TextBlock dp:ElementDataContext.ElementName="LvMain">

我验证了属性ElementDataContext.ElementName被设置为"LvMain"。

现在这里是问题:在TextBlock的上下文菜单中,我想通过PlacementTarget 绑定到这个依赖属性

我是这样做的。这是我的包含TextBlockContextMenu的XAML的摘录:

<TextBlock dp:ElementDataContext.ElementName="LvMain">
    <TextBlock.ContextMenu>
        <ContextMenu Tag="{Binding PlacementTarget.(dp:ElementDataContext.ElementName), RelativeSource={RelativeSource Self}}">

这在运行时失败。当打开上下文菜单时,它给了我一个"BindingExpression路径错误":

BindingExpression path error: '(dp:ElementDataContext.ElementName)' property not found on 'object' ''TextBlock' (Name='')'. BindingExpression:Path=PlacementTarget.(dp:ElementDataContext.ElementName); DataItem='ContextMenu' (Name='contextMenu'); target element is 'ContextMenu' (Name='contextMenu'); target property is 'Tag' (type 'Object')

我怀疑我的绑定路径错误。我试着

  • PlacementTarget.(dp:ElementDataContext.ElementName)
  • PlacementTarget.dp:ElementDataContext.ElementName
  • PlacementTarget.ElementDataContext.ElementName

没有效果。正确的语法是什么?这可能吗?

属性路径语法PlacementTarget.(dp:ElementDataContext.ElementName)是正确的,但是您还必须在属性表达式中显式地编写Path=...部分:

<ContextMenu Tag="{Binding Path=PlacementTarget.(dp:ElementDataContext.ElementName),
                           RelativeSource={RelativeSource Self}}">

然而,绑定标记扩展中的隐式路径部分并没有提到这种行为。

最新更新