passing the current Window as a CommandParameter

SwissCoder picture SwissCoder · Aug 17, 2010 · Viewed 25k times · Source

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?-" />

Answer

Daniel Pratt picture Daniel Pratt · Aug 17, 2010

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}}}" />