代码之家  ›  专栏  ›  技术社区  ›  SwissCoder

将当前窗口作为CommandParameter传递

  •  21
  • SwissCoder  · 技术社区  · 15 年前

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

    <Button Command="CommandGetsCalled" CommandParameter="-this?-" />
    
    3 回复  |  直到 15 年前
        1
  •  70
  •   Daniel Pratt    15 年前

    我有两种方法可以做到这一点:给窗口一个名字(通过 x:Name Window

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

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

    <Button Command="CommandGetsCalled" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" /> 
    
        2
  •  21
  •   Rachel    15 年前

    你可以尝试绑定到相对资源

    如果要将按钮作为参数传递:

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

    <Button Command="CommandGetsCalled" 
            CommandParameter="{Binding RelativeSource={
                 RelativeSource AncestorType={x:Type Window}}}" />
    
        3
  •  6
  •   The One    8 年前

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

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