Caliburn命令评估只发射了一次

本文关键字:一次 命令 评估 发射 Caliburn | 更新日期: 2023-09-27 18:04:22

我正试图使用Caliburns'Can'约定在视图上启用一个按钮,用于视图模型属性评估。

视图(摘录(

<PasswordBox PasswordChanged="PasswordBox_OnPasswordChanged" Grid.Row="1" Grid.Column="1" />
...
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
    <Button Content="Cancel" cal:Message.Attach="[Event Click] = [Action Cancel]" />
    <Button Content="Login" cal:Message.Attach="[Event Click] = [Action Login]" />
</StackPanel>

代码隐藏

private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e)
{
    if (DataContext != null)
        ((dynamic) DataContext).Password = ((PasswordBox) sender).Password;
}

ViewModel

public class LoginSplashViewModel : Screen
{
    private string _username;
    private string _password;
    public string Username
    {
        get { return _username; }
        set
        {
            _username = value;
            NotifyOfPropertyChange();
        }
    }
    public string Password
    {
        get { return _password; }
        set
        {
            _password = value;
            NotifyOfPropertyChange();
        }
    }
    public LoginSplashViewModel()
    {
        DisplayName = "Login";
    }
    public bool CanLogin()
    {
        return  !string.IsNullOrEmpty(_username) || 
                !string.IsNullOrEmpty(_password);
    }
    public void Login()
    {
        TryClose(true);
    }
    public void Cancel()
    {
        TryClose(false);
    }
}

但是,'CanLogin()'方法只触发一次(当将视图模型绑定到视图时(,并且再也不会触发,因此按钮保持禁用状态。

我是不是遗漏了什么?

Caliburn命令评估只发射了一次

 public string Password{
  get{ return _password;}
  set{
     _password = value;
     NotifyOfPropertyChange();
     NotifyOfPropertyChange(() => CanLogin);   // <--- Addition
   }
 } 

用户名也是如此。。。

值得一提的是,你也不必参加冗长的活动。。。你可以做
<Button x:Name="Login" />

这就是命令在Caliburn中的实现方式。基本上,在ICommand实现者中,可以调用一个东西来强制重新评估CanExecute方法。

只要有可以在代码隐藏或视图模型中识别的更改。此外,您还可以选择自己实现该命令并避免这种必要性。