2016-07-22 5 views
1

タイトルが離れてあなたを怖がらなかった場合、ここでは、基本的に、私はコンテキストメニューを持っている...WPF Resources.ContextMenu.MenuItem。(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> 

を行きます2つのメニュー項目を持つ...最初の(コピー)は常に利用可能です... 2番目の(追加)は、コンテキストメニューが添付されたプロパティを持つUIElementから適用される場合にのみ使用できます。

この作品のほとんどは、添付されたプロパティがプロキシリソースを介して正しくバインディングされているため、menuitemのクリックイベントが添付プロパティの値を取得できます。

私は当初は可視性をバインドしようとしていましたが、最近は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への結合のMenuItemに関する)を見つけることができましたすべての記事や例がUIElementの上で直接コンテキストメニューを持っている、と窓/コントロールがインスタンス化されたときに結合が生じるので、コンテキストメニューが表示される前に)、私はPlacementTargetがNULLなので、エラーだと思っています。

Thxで事前に!

答えて

1

問題は、RelativeSourceを割り当てるためにバインディングのSourceプロパティを使用していることです。それは次のようになります。

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

エラーを見れば、それは実際にそれを説明する:

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

オブジェクトは、コンテキストメニューしてきたはずです。

+0

私のコードを調整する必要があります(現在は結果が後方にあります)...しかし、エラーは表示されず、コンテキストメニューのさまざまな使い方によって結果の違いが示されています。それは...確定した後に授与されます –

+0

うん、それは...賞金は私ができるだけ早く授与される...私はソースが抽象であり、RelativeSourceが実装であったと思った...明らかにそうではない。 .. thx again! –

+0

いいえ、 'Source'では、ソースオブジェクトを直接指定できます。主にC#でバインディングを作成するときに使用されます。 –