Hi,
please, use another HelperCommand and your code work. Try following demo:
using System;
using System.Windows;
using System.Windows.Input;
namespace WpfApp055
{
public class ViewModel
{
public ICommand LoginCommand { get => new HelperCommand(RegisterUser, CanRegister); }
private void RegisterUser(object parameter)
{
Window wnd = parameter as Window;
wnd?.Close();
}
private bool CanRegister(object parameter) => true;
}
public class HelperCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public HelperCommand(Action<object> execute) : this(execute, canExecute: null) { }
public HelperCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null) throw new ArgumentNullException("execute");
this._execute = execute;
this._canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) => this._canExecute == null ? true : this._canExecute(parameter);
public void Execute(object parameter) => this._execute(parameter);
public void RaiseCanExecuteChanged() => this.CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
And XAML:
<Window x:Class="WpfApp1.Window055"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp055"
mc:Ignorable="d"
Title="Close Window" Height="450" Width="800"
x:Name="window">
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<StackPanel>
<Button Content="Close Window"
Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=window, Mode=OneWay}"/>
</StackPanel>
</Window>