passing the current Window as a CommandParameter

痴心易碎 提交于 2019-11-30 13:10:03

问题


how can I pass the window I am currently on as a parameter to a command?

I like to do this in XAML-markup:

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

回答1:


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'):

<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}}}" /> 



回答2:


You could try binding to a RelativeSource

If you want to pass the Button as a parameter:

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

If you want to pass the Window as a parameter:

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



回答3:


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>


来源:https://stackoverflow.com/questions/3504332/passing-the-current-window-as-a-commandparameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!