29

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?-" />
SwissCoder
  • 2,514
  • 4
  • 28
  • 40
  • Why? There is no "this" notation in XAML as far as I know. Besides, `this` in this case would probably be the button. What are you trying to do? – Dave White Aug 17 '10 at 15:59
  • with -this- I meant the containing Window object. I write it in the title and in in the text, that I want to pass the window. As the answers of Rachel and Daniel Pratt show, its clear enough ;) – SwissCoder Aug 17 '10 at 20:45

3 Answers3

73

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}}}" /> 
Daniel Pratt
  • 12,007
  • 2
  • 44
  • 61
24

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}}}" />
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • Thank you Rachel. I looked at your and Daniel Pratt's solutions. Actually they are quite similar. But I'll mark his as answer, because I like the idea of accessing the Window via its name. – SwissCoder Aug 17 '10 at 20:52
  • I'm getting `Specified Visual is already a child of another Visual or the root of a CompositionTarget.` when I try to use the `Button` as a parameter example. any ideas? – Maslow Jan 17 '17 at 21:09
  • found out it's because I was trying to `.Dump()` the button in the `canExecute` via `LinqPad` which would wpf display it – Maslow Jan 17 '17 at 21:15
7

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>
The One
  • 4,560
  • 5
  • 36
  • 52