将当前窗口作为CommandParameter传递

29

我怎样把当前窗口作为参数传递给一个命令?

我想在XAML标记中实现这个功能:

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

为什么?据我所知,XAML中没有“this”符号。此外,在这种情况下,“this”可能是指按钮。你想做什么? - Dave White
我在这里指的是包含的窗口对象。我在标题和文本中都写了,我想传递窗口。正如Rachel和Daniel Pratt的回答所示,这已经很清楚了 ;) - SwissCoder
3个回答

73

我可以想到两种方法来实现这个:给窗口命名(通过在Window标记上使用x:Name属性),然后构建一个绑定,如下所示(假设窗口的名称为'ThisWindow'):

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

如果需要更通用的绑定方法(不依赖于为当前窗口命名),可以按照以下方式构建绑定:

<Button Command="CommandGetsCalled" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" /> 

1
请问您能否展示一下这在ViewModel中的样子? - CeOnSql

24
你可以尝试绑定到一个相对源。如果你想将按钮作为参数传递:
<Button Command="CommandGetsCalled" 
        CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />

如果你想将窗口作为参数传递:

<Button Command="CommandGetsCalled" 
        CommandParameter="{Binding RelativeSource={
             RelativeSource AncestorType={x:Type Window}}}" />

谢谢Rachel。我看了你和Daniel Pratt的解决方案。实际上它们非常相似。但是我会将他的标记为答案,因为我喜欢通过名称访问窗口的想法。 - SwissCoder
当我试图将“Button”作为参数示例使用时,出现“指定的可视对象已经是另一个可视对象的子元素或组合目标的根”的错误。有什么想法吗? - Maslow
发现问题是因为我试图通过 LinqPadcanExecute 中使用 .Dump() 来显示 WPF 按钮。 - Maslow

7

在我的情况下,提供的答案都没有起作用。

这个方法对我有用:

<window x:Name="myWindow">
 <Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接