1:定义公用关闭类
public class CommandBase : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return DoCanExecute?.Invoke(parameter) == true;
}
public void Execute(object parameter)
{
DoExecute?.Invoke(parameter);
}
public Action<object> DoExecute { get; set; }
public Func<object, bool> DoCanExecute { get; set; }
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, new EventArgs());
}
}
2:定义视图的模型方法
public class LoginViewModel : NotifyBase
{
public CommandBase LoginCommand { get; set; }
public LoginViewModel()
{
this.CloseWindowCommand = new CommandBase();
this.CloseWindowCommand.DoExecute = new Action<object>((o) =>
{
(o as Window).Close();
});
this.CloseWindowCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });
}
}
3:挂在到窗体上
public partial class LoginView : Window
{
public LoginView()
{
InitializeComponent();
this.DataContext = new LoginViewModel();
}
}
4:窗体上使用
<Window
mc:Ignorable="d" Name="window"
>
<Button VerticalAlignment="Top" HorizontalAlignment="Right"
Style="{StaticResource WindowControlButtonStyle}" Content=""
Command="{Binding CloseWindowCommand}"
CommandParameter="{Binding ElementName=window}">
></Window>