How to Bind to window's close button the X-button

后端 未结 4 1848
长情又很酷
长情又很酷 2020-12-20 22:55

How I can bind one of my buttons on control to X Button that closes the window ? I just want to create cancel button that just closes the window. I am using MVVM in my code.

相关标签:
4条回答
  • 2020-12-20 23:25

    Install Microsoft.Expression.Interactions by nugget and use the answer gived by Chris W. above.

    0 讨论(0)
  • 2020-12-20 23:42

    MVVM solution without code-behind could also look like this:

    View:

    <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);
        }
    }
    

    But SystemCommands is from .net-4.5 so if you rock in some older version of .net you can also use following.

    public ICommand CloseWindowCommand
    {
        get
        {
            return new RelayCommand<Window>((window) => window.Close());
        }
    }
    
    0 讨论(0)
  • 2020-12-20 23:43

    You can just call the Close() method, which will close the window.

    private void MyButton_Click(object s, RoutedEventArgs e)
    {
        Close();
    }
    
    0 讨论(0)
  • 2020-12-20 23:48

    If it's WPF (and provided I remember right) you can just use CallMethodAction from the parent as a behavior and utilize Close() method via just XAML. Something like;

    Parent Window x:Name="window"

    namespaces;

     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>
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题