2016-07-22 68 views
1

如果標題沒有嚇唬你了,這裏去...WPF Resources.ContextMenu.MenuItem結合ContextMenu.PlacementTarget。(AttachedProperty)

<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事件能夠獲得附加屬性值。 (最初我想要綁定可見性,但最近我在想IsEnabled對於UX來說是一個更好的主意)。不能工作的唯一的事情就是MenuItem.IsEnabled/Visibility綁定。

錯誤在綁定中。輸出窗口中出現標準錯誤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') 

事情是,每一篇文章或例子,我已經能夠找到(關於菜單項結合PlacementTarget)直接對UIElement的上下文菜單中,當窗口/控件被實例化,因爲發生結合(在顯示上下文菜單之前),我在考慮PlacementTarget爲NULL,從而導致錯誤。

Thx提前!

回答

1

問題是您使用綁定的Source屬性來分配RelativeSource。它應該是:

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

如果你看一下錯誤,它實際上解釋了它:

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

的對象應該已經上下文菜單。

+0

需要調整我的代碼有點(現在條件結果是倒退)...但我沒有看到錯誤,並且上下文菜單的不同用途顯示結果的差異...很確定這得到了它!!獎勵一旦確認 –

+0

是的,你知道了......賞金將盡快頒發......我認爲Source是一個抽象,並且RelativeSource是實現......顯然並非如此。 .. thx再次! –

+0

不,'Source'可以讓你直接指定源對象。主要用於在C#中創建綁定。 –