将当前窗口作为CommandParameter传递

问题描述 投票:22回答:3

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

我喜欢在XAML-markup中执行此操作:

<Button Command="CommandGetsCalled" CommandParameter="-this?-" />
wpf binding commandparameter
3个回答
60
投票

我可以通过两种方式来做到这一点:给窗口命名(通过x:Name标签上的Window属性,然后构造一个这样的绑定(假设窗口的名称是'ThisWindow'):

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

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

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

20
投票

您可以尝试绑定到RelativeSource

如果要将Button作为参数传递:

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

如果要将Window作为参数传递:

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

2
投票

在我的情况下,所提供的答案都没有奏效。

这对我有用:

<window x:Name="myWindow">
 <Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>
© www.soinside.com 2019 - 2024. All rights reserved.