如何绑定到窗口'

本文关键字:窗口 何绑定 绑定 | 更新日期: 2023-09-27 18:14:00

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

如何绑定到窗口'

您可以直接调用Close()方法,它将关闭窗口。

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

如果它是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>

没有代码隐藏的MVVM解决方案也可能是这样的:

视图:

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

ViewModel:

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

但是SystemCommands来自。net 4.5,所以如果你使用的是。net的旧版本,你也可以使用下面的命令。

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