题
如何将目前作为参数的窗口传递给命令?
我喜欢在xaml-markup中这样做:
<Button Command="CommandGetsCalled" CommandParameter="-this?-" />
解决方案
我有两种方法可以考虑这样做:给窗户一个名字(通过 x:Name
属性 Window
标签,然后构造这样的绑定(假设窗口的名称为'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}}}" />
在我的情况下,提供的答案都没有。
这对我有用:
<window x:Name="myWindow">
<Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>
不隶属于 StackOverflow