Подтвердить что ты не робот

Кнопка закрытия окна управления в wpf MVVM

Есть ли способ обработать кнопку закрытия окна, то есть "X" в верхнем правом углу в режиме просмотра, привязывая к команде? или переопределить команду window.close, чтобы закрытие одного окна возвращалось к предыдущему окну. Thanx.

4b9b3361

Ответ 1

Для этого существует несколько методов. Я указал на два метода ниже.

  • Вы можете использовать прикрепленные команды для привязки кнопки закрытия в своей модели просмотра.

  • Вы можете использовать код ниже

Xaml:

<Window x:Class="WpfInfragisticsModal.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" 
        xmlns:ig="http://schemas.infragistics.com/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        Name="myWindow">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Closing">
            <i:InvokeCommandAction Command="{Binding CloseWindowCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>
    </Grid>
</Window>

ПРИМЕЧАНИЕ. Добавьте ссылку System.Windows.Interactivity

Просмотр модели

private ICommand closeWindowCommand;

public ICommand CloseWindowCommand
{
      get
      {
          if (closeWindowCommand == null)
          {
             closeWindowCommand = new RelayCommand(param => this.CloseWindow(), null);
          }
          return closeWindowCommand;
      }
 }

private void CloseWindow()
{
     //Do your operations
}

Это мой класс RelayCommand.

public class RelayCommand : ICommand
{
    /// <summary>
    /// Initializes a new instance of the <see cref="RelayCommand"/> class.
    /// </summary>
    /// <param name="execute">The execute.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="RelayCommand"/> class.
    /// </summary>
    /// <param name="execute">The execute.</param>
    /// <param name="canExecute">The can execute.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Defines the method that determines whether the command can execute in its current state.
    /// </summary>
    /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
    /// <returns>
    /// true if this command can be executed; otherwise, false.
    /// </returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    /// <summary>
    /// Occurs when changes occur that affect whether or not the command should execute.
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Defines the method to be called when the command is invoked.
    /// </summary>
    /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    /// <summary>
    /// Action
    /// </summary>
    private readonly Action<object> _execute;


    /// <summary>
    /// Predicate
    /// </summary>
    private readonly Predicate<object> _canExecute;
}

Ответ 2

проблема заключалась в том, что я закрывал родительское окно и снова открывал его после закрытия своего дочернего окна, вызывая утечку памяти. Я решил, скрыв родительское окно, а затем снова показывая его после закрытия дочернего окна. Я новичок в разработке wpf и windows, поэтому я узнаю, как я иду.