将当前窗口作为CommandParameter传递

将当前窗口作为CommandParameter传递

问题描述:

如何将当前打开的窗口作为参数传递给命令?

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

我喜欢在XAML标记中这样做:

I like to do this in XAML-markup:

<Button Command="CommandGetsCalled" CommandParameter="-this?-" />

我可以想到两种方法:为窗口命名(通过Window标记上的x:Name属性,然后构造一个这样的绑定(假设窗口的名称是"ThisWindow"):

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

对于更通用的东西(不依赖于给当前Window命名),可以这样构造绑定:

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