将当前窗口作为命令参数传递

发布于 2024-09-14 21:25:44 字数 153 浏览 2 评论 0原文

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

我喜欢在 XAML 标记中执行此操作:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

給妳壹絲溫柔 2024-09-21 21:25:44

我可以想到两种方法来做到这一点: 为窗口命名(通过 Window 标记上的 x:Name 属性,然后构造一个像这样的绑定(假设窗口的名称是“ThisWindow”):

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

对于更一般的情况(不依赖于为当前窗口指定名称),可以像这样构造绑定:

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

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}}}" /> 
聚集的泪 2024-09-21 21:25:44

您可以尝试绑定到RelativeSource

如果您想将Button 作为参数传递:

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

如果您想将Window 作为参数传递:

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

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}}}" />
嗳卜坏 2024-09-21 21:25:44

在我的情况下,所提供的答案都不起作用。

这对我有用:

<window x:Name="myWindow">
 <Button Command="Command" CommandParameter={x:Reference Name=myWindow}/>
</window>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文