Caliburn 微动作

Caliburn Micro actions

我对一件事感到困惑。当我从称为 ClearTextCanClearText 的方法(或其中之一)中删除参数 (string firstName) 时,清除数据后按钮不会被禁用。

你能解释一下发生了什么吗?

这是属性;

public string FirstName
{
    get
    {
        return _firstName;
    }
    set
    {
        _firstName = value;
        NotifyOfPropertyChange(() => FirstName);
    }
}

这些是方法:

public bool CanClearText(string firstName)
{
    return !string.IsNullOrWhiteSpace(FirstName);
}

public void ClearText(string firstName)
{
    FirstName = "";
}

这是对应的文本框和按钮

<TextBox x:Name ="FirstName" MinWidth="100" Grid.Column="1" Grid.Row="2"></TextBox>
<Button Grid.Row="4" Grid.Column="1" x:Name="ClearText"> Clear Names </Button>

从技术上讲,您没有使用传递给 action 和 guard 的参数,因此实际上没有必要。

您也可以将属性用作动作守卫

public string FirstName {
    get {
        return _firstName;
    }
    set {
        _firstName = value;
        NotifyOfPropertyChange(() => FirstName);
        NotifyOfPropertyChange(() => CanClearText);
    }
}

public bool CanClearText {
    get {
        return !string.IsNullOrEmpty(FirstName);
    }
}

public void ClearText() {
    FirstName = "";
}

之前发生的事情是 UI 没有意识到关于行动守卫的任何变化。使用 属性 方法并通知 UI 它应该重新检查守卫将更新按钮的可用性。

Any 通过使用 属性 方法,您还可以利用绑定到 action guard 的优势。比如

如果没有理由清除文本,因为它是空的,那么您也可以隐藏按钮。

<TextBox x:Name ="FirstName" MinWidth="100" Grid.Column="1" Grid.Row="2"></TextBox>
<Border x:Name="CanClearText" Grid.Row="4" Grid.Column="1">
    <Button x:Name="ClearText" Content="Clear Names" />
</Border>

通过 Caliburn.Micro 将 CanClearText 边框的可见性自动绑定到 属性 它会在 CanClearText 属性 为 false 时隐藏.