如何绑定窗口的关闭按钮X按钮

时间:2013-05-15 20:01:32

标签: c# wpf xaml mvvm

如何将控件上的一个按钮绑定到关闭窗口的X按钮? 我只想创建关闭窗口的取消按钮。 我在我的代码中使用MVVM。 如果可能只在xaml中进行,我只是没有点击按钮的任何特殊代码。

4 个答案:

答案 0 :(得分:7)

您只需调用Close()方法即可关闭窗口。

private void MyButton_Click(object s, RoutedEventArgs e)
{
    Close();
}

答案 1 :(得分:3)

如果它是WPF(并提供我记得正确),您可以使用父项中的CallMethodAction作为行为,并通过XAML使用Close()方法。喜欢的东西;

父窗口x:Name="window"

命名空间;

 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

-

<Button Content="Cancel">
    <i:Interaction.Triggers>
      <i:EventTrigger EventName="Click">
        <ei:CallMethodAction
            TargetObject="{Binding ElementName=window}"
            MethodName="Close"/>
      </i:EventTrigger>
    </i:Interaction.Triggers>
  </Button>

希望这有帮助。

答案 2 :(得分:3)

没有代码隐藏的MVVM解决方案也可能如下所示:

查看:

<Button Content="Cancel" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />

<强>视图模型:

public ICommand CloseWindowCommand
{
    get
    {
        return new RelayCommand<Window>(SystemCommands.CloseWindow);
    }
}

但是SystemCommands来自,所以如果您使用某些旧版本的,您也可以使用以下内容。

public ICommand CloseWindowCommand
{
    get
    {
        return new RelayCommand<Window>((window) => window.Close());
    }
}

答案 3 :(得分:0)

使用nugget安装Microsoft.Expression.Interactions并使用上面Chris W.给出的答案。