PropertyChanged被触发,但视图没有更新

Con*_*nst 2 xamarin.ios xamarin.android xamarin xamarin.forms

我正在更改类构造函数中的标签,它工作正常,标签已更新(“0”)。当我单击按钮时,我还尝试更新标签,但它不起作用(“X”)。我注意到调试标签值已更新,PropertyChanged 被触发,但视图没有更改。

public class HomeViewModel : ViewModelBase
{
    string playerA;
    public string PlayerA
    {
        get
        {
            return playerA;
        }
        set
        {
            playerA = value;
            this.Notify("playerA");
        }
    }

    public ICommand PlayerA_Plus_Command
    {
        get;
        set;
    }

    public HomeViewModel()
    {
        this.PlayerA_Plus_Command = new Command(this.PlayerA_Plus);
        this.PlayerA = "0";
    }

    public void PlayerA_Plus()
    {
        this.PlayerA = "X";
    }
}



public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Notify(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

Kru*_*lur 5

你传入的参数名称PropertyChangedEventArgs是错误的。您正在使用“playerA”,但(公共)属性的名称是“PlayerA”(大写“P”)。更改this.Notify("playerA");this.Notify("PlayerA");或什至更好:

Notify(nameof(PlayerA));

您可以通过向方法添加[CallerMemberName] 属性来完全摆脱传递参数名称Notify()

protected void Notify([CallerMemberName] string propertyName = null)

这允许您只需调用Notify()而不带参数,并且将自动使用更改的属性的名称。