当其 CanX 属性 returns true 时 Stylet Button 未启用

Stylet Button not enabling when its CanX property returns true

使用Stylet

我在 dotnet core 3.1 中使用默认的 Stylet 模板。 我只是添加了一个 property/method 来重现问题。

<TextBox Text="{Binding Username, 
                Mode=TwoWay, 
                UpdateSourceTrigger=PropertyChanged}" 
         Width="100" Height="100"/>

<Button Command="{s:Action Do}">Foo</Button>
public class ShellViewModel : Screen
{
    public string Username { get; set; }

    public void Do() { }

    public bool CanDo => !string.IsNullOrWhiteSpace(Username);
}

CanDo属性 上的断点被命中一次,再也不会命中。在调用 set 时更改 TextBox 中的值不会重新触发 CanDo 属性。

我也尝试过将支持字段与 SetAndNotify 一起使用,但无济于事:

public string Username { get => username; set => SetAndNotify(ref username, value, nameof(Username)); }

我发现我缺少 属性 更改通知。通过我看到的所有示例,我假设这是由 Stylet 为我隐式处理的。

将我的 属性 setter 更改为以下内容后,它按预期工作。

public string Username
{
    get => _username;
    set
    {
        SetAndNotify(ref _username, value);
        NotifyOfPropertyChange(() => CanLogin);
    }
}

PropertyChangedBase also takes care to integrate with Fody.PropertyChanged. Notifications raised by Fody.PropertyChanged are raised using the PropertyChangedDispatcher.

Therefore you do not need to do anything special in order to use Fody.PropertyChanged with any subclass of Screen, ValidatingModelBase, or PropertyChangedBase.

这来自 Stylet 文档 wiki。如果一个项目正在使用 Fody.PropertyChanged,则它不必手动编写 NotifyOfPropertyChange(),这可能就是您在示例代码中没有看到 NotifyOfPropertyChange() 的原因。

Fody.PropertyChanged 是一个很棒的包,试试吧,它为我节省了数百万次击键:)