WPF Resources.ContextMenu.MenuItem绑定到ContextMenu.PlacementTarget。(AttachedProperty)

时间:2016-07-22 19:44:28

标签: wpf binding contextmenu menuitem resourcedictionary

如果标题没有吓跑你,这就是......

<UserControl.Resources>
    <!-- so the attached CustomObject can bind to the context -->
    <my:BindingProxy x:Key="DataContextProxy" Data="{Binding}" />

    <!-- for chaining IsNull to Visibility.Collapsed -->
    <my:ConverterGroup x:Key="IsNullToVisibility">
        <my:IsNullConverter />
        <my:VisibilityValuesEqual />
    </my:ConverterGroup>

    <ContextMenu x:Key="ctxmnu">
        <MenuItem Header="Copy"   Click="ctxmnu_itmCopy_Click" />
        <MenuItem Header="Add"    Click="ctxmnu_itmAdd_Click"
                  IsEnabled="{Binding  Source={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu},
                                       Path=PlacementTarget,
                                       Converter={StaticResource IsNotNullConverter}}"
                  Visibility="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu},
                                       Path=PlacementTarget.(myAP:APClass.Property),
                                       Converter={StaticResource IsNullToVisibility}}"
                  />
    </ContextMenu>
</UserControl.Resources>


    <Label Content="{Binding Path=Description}" ContextMenu="{StaticResource ctxmnu}">
        <myAP:APClass.Property>
            <myAP:CustomObject ID="{Binding Source={StaticResource DataContextProxy}, Path=ID}" />
        </myAP:APClass.Property>
    </Label>

</UserControl>

基本上,我有一个上下文菜单,有两个菜单项......第一个(副本)始终可用...第二个(添加)仅在从UIElement应用上下文菜单时可用附属物。

大部分工作......附加属性通过代理资源正确绑定,menuitem click事件能够获取附加的属性值。

唯一不起作用的是MenuItem.IsEnabled / Visibility绑定(我最初会绑定可见性,但最近我认为IsEnabled对于UX来说更好)。

错误在绑定中。输出窗口中的标准错误40。

System.Windows.Data
 Error: 40 :
 BindingExpression path error:
 'PlacementTarget' property not found on 'object' ''RelativeSource' (HashCode=22838427)'.
 BindingExpression:Path=PlacementTarget.(0); DataItem='RelativeSource' (HashCode=22838427);
 target element is 'MenuItem' (Name='');
 target property is 'Visibility' (type 'Visibility')

事实是,我能找到的每篇文章或示例(关于MenuItem绑定到PlacementTarget)都直接在UIElement上有上下文菜单,并且因为绑定发生在实例化窗口/控件时(在上下文菜单之前)如图所示),我认为PlacementTarget为NULL,因而错误。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

问题是您使用绑定的Source属性来分配RelativeSource。它应该是:

IsEnabled="{Binding RelativeSource={RelativeSource
                    ^^^^^^^^^^^^^^

如果您查看错误,它实际上会解释它:

'PlacementTarget' property not found on 'object' ''RelativeSource'

该对象应该是上下文菜单。