(精华)2020年01月24日 WPF课程管理系统项目实战(登陆界面-关闭逻辑实现)

149 阅读1分钟

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:挂在到窗体上

 /// <summary>
 /// LoginView.xaml 的交互逻辑
 /// </summary>
 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="&#xe653;"
                    Command="{Binding CloseWindowCommand}"
                    CommandParameter="{Binding ElementName=window}">
></Window>