Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing the current Window as a CommandParameter

how can I pass the window I am currently on as a parameter to a command?

I like to do this in XAML-markup:

<Button Command="CommandGetsCalled" CommandParameter="-this?-" />
like image 542
SwissCoder Avatar asked Aug 17 '10 15:08

SwissCoder


3 Answers

There are two ways I can of think to do this: Give the window a name (via a x:Name attribute on the Window tag, and then construct a binding like this (assumes the name of the window is 'ThisWindow'):

<Button Command="CommandGetsCalled" CommandParameter="{Binding ElementName=ThisWindow}" />

For something more general (doesn't rely on giving the current Window a name), the binding can be constructed like this:

<Button Command="CommandGetsCalled" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" /> 
like image 144
Daniel Pratt Avatar answered Oct 11 '22 04:10

Daniel Pratt


You could try binding to a RelativeSource

If you want to pass the Button as a parameter:

<Button Command="CommandGetsCalled" 
        CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />

If you want to pass the Window as a parameter:

<Button Command="CommandGetsCalled" 
        CommandParameter="{Binding RelativeSource={
             RelativeSource AncestorType={x:Type Window}}}" />
like image 39
Rachel Avatar answered Oct 11 '22 03:10

Rachel


In my situation none of the provided answers worked.

This worked for me:

<window x:Name="myWindow">
 <Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>
like image 44
The One Avatar answered Oct 11 '22 04:10

The One