2016-10-19 4 views
0

コンテンツコントロールにはいくつかのボタンがあり、それぞれが押されて解放されるタイミングを知りたいと思います。私の研究から、これを行う唯一の方法はインタラクショントリガを使用することですが、より簡単な方法があれば修正します。ContentControl WPFのインタラクショントリガーのCommandParameterとしての名前

私は10+のボタンを持っている、とのPreviewMouseLeftButtonDownのPreviewMouseLeftButtonUpを割り当てること、ボタンごとに8行までかかるので、私は私UserControl.Resourcesで、このように再利用できるカスタムボタンに定義:

<UserControl.Resources> 
    <Button x:Key="ButtonWTriggers" x:Shared="False"> 
     <inter:Interaction.Triggers> 
      <inter:EventTrigger EventName="PreviewMouseLeftButtonDown"> 
       <inter:InvokeCommandAction Command="{Binding ButtonDownCmd}" CommandParameter="{Binding Path=Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}}"/> 
      </inter:EventTrigger> 
      <inter:EventTrigger EventName="PreviewMouseLeftButtonUp"> 
       <inter:InvokeCommandAction Command="{Binding ButtonUpCmd}" CommandParameter="{Binding Path=Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}}"/> 
      </inter:EventTrigger> 
     </inter:Interaction.Triggers> 
    </Button>  
</UserControl.Resources> 

<ContentControl Name="testbutton" Content="{StaticResource ButtonWTriggers}"/> 

をし、私私は、コマンドのパラメータとしてContentControl Name=<NAME HERE>を使用して考えていた、リソースを複数回使用しているので

<ContentControl Name="testbutton" Content="{StaticResource ButtonWTriggers}"/> 

、と私はどのボタンが押された正確に知りたい:「でそれを使用してメートル。 CommandParameter="{Binding Path=Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}}"でその名前を取得しようとしましたが、動作しません。 PressとReleaseのアクションは実行されますが、パラメータが空です。おそらく、コンテンツコントロールの代わりにボタンのnameプロパティを取得しようとしているからでしょうか?

トリガーコマンドのパラメータとしてContentControlの名前を取得する手助けがありますか?あなたの問題に対処するための

答えて

1

一つの方法は、Button自体をスキップするRelativeSource.AncestorLevelプロパティを使用することです:

<inter:InvokeCommandAction (...) CommantParameter="{Binding Name, RelativeSource={RelativeSource AncestorType=ContentControl, AncestorLevel=2}}" /> 

しかし、それは例えばButtonのテンプレート場合は動作を停止しますので、私はそれは非常に信頼性の低い考えますContentControlが含まれています(相対元は再びButtonに解決されます)。

<Button (...) Tag="{Binding Name, RelativeSource={RelativeSource AncestorType=ContentControl}}"> 
    (...) 
    <inter:InvokeCommandAction (...) CommandParameter="{Binding Tag, RelativeSource={RelativeSource AncestorType=Button}}" /> 
    (...) 
</Button> 

はすでに何か他のもののためにButton.Tagプロパティを使用しかし、もし:私の意見では

はるかに信頼性の高いソリューションは、その先祖の名前にButton.Tagプロパティをバインドして、代わりにそのプロパティにInvokeCommandAction.CommandParameterをバインドすることですこれらの方法にもかかわらず、それはトン、あなたの特定のケースでは同じですけれども

<inter:InvokeCommandAction (...) CommantParameter="{Binding Parent.Name, RelativeSource={RelativeSource AncestorType=Button}}" /> 

注:、中間体溶液はButton.Parentプロパティを利用することであろうねえ、一般的には同等ではないので、賢明に選んでください。

+0

実際に初めてTagプロパティを使用するので、2番目のソリューションがうまく機能します。ありがとうございました! –

関連する問題