wpf 将当前窗口作为 CommandParameter 传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3504332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing the current Window as a CommandParameter
提问by SwissCoder
how can I pass the window I am currently on as a parameter to a command?
如何将当前所在的窗口作为参数传递给命令?
I like to do this in XAML-markup:
我喜欢在 XAML 标记中这样做:
<Button Command="CommandGetsCalled" CommandParameter="-this?-" />
回答by Daniel Pratt
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'):
我可以想到两种方法来做到这一点:给窗口一个名称(通过标签上的x:Name
属性Window
,然后构造一个这样的绑定(假设窗口的名称是“ThisWindow”):
<Button Command="CommandGetsCalled" CommandParameter="{Binding ElementName=ThisWindow}" />
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}}}" />
回答by Rachel
You could try binding to a RelativeSource
您可以尝试绑定到一个 RelativeSource
If you want to pass the Button as a parameter:
如果要将 Button 作为参数传递:
<Button Command="CommandGetsCalled"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
If you want to pass the Window as a parameter:
如果要将 Window 作为参数传递:
<Button Command="CommandGetsCalled"
CommandParameter="{Binding RelativeSource={
RelativeSource AncestorType={x:Type Window}}}" />
回答by The One
In my situation none of the provided answers worked.
在我的情况下,提供的答案都不起作用。
This worked for me:
这对我有用:
<window x:Name="myWindow">
<Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>