我怎样把当前窗口作为参数传递给一个命令?
我想在XAML标记中实现这个功能:
<Button Command="CommandGetsCalled" CommandParameter="-this?-" />
我怎样把当前窗口作为参数传递给一个命令?
我想在XAML标记中实现这个功能:
<Button Command="CommandGetsCalled" CommandParameter="-this?-" />
我可以想到两种方法来实现这个:给窗口命名(通过在Window
标记上使用x:Name
属性),然后构建一个绑定,如下所示(假设窗口的名称为'ThisWindow'):
<Button Command="CommandGetsCalled" CommandParameter="{Binding ElementName=ThisWindow}" />
如果需要更通用的绑定方法(不依赖于为当前窗口命名),可以按照以下方式构建绑定:
<Button Command="CommandGetsCalled" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" />
<Button Command="CommandGetsCalled"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
如果你想将窗口作为参数传递:
<Button Command="CommandGetsCalled"
CommandParameter="{Binding RelativeSource={
RelativeSource AncestorType={x:Type Window}}}" />
LinqPad
在 canExecute
中使用 .Dump()
来显示 WPF 按钮。 - Maslow在我的情况下,提供的答案都没有起作用。
这个方法对我有用:
<window x:Name="myWindow">
<Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>