xamarin 当可绑定对象的一部分更新时,BindableProperty不更新

tf7tbtn2  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(108)

我正在尝试从父级中的绑定使用BindableProperty。
Header.xaml.cs:

public static readonly BindableProperty UserProperty = BindableProperty.Create(
             nameof(User),
             typeof(User),
             typeof(Header),
             null,
             defaultBindingMode: BindingMode.TwoWay,
             propertyChanged: UpdateUser
        );

        private static void UpdateUser(BindableObject bindable, object oldValue, object newValue)
        {
            var control = bindable as Header;
            control.OnLoggedInLoggedOut((User) newValue);
        }

用户来自ChallengeViewModel. cs:

private User user;
        public User User
        {
            get
            {
                return user;
            }
            set
            {
                user = value;
                OnPropertyChanged();
                OnLoginLogout();
            }
        }

如果我用一个新对象更新整个User对象,例如User = new User();如果我只更新对象的一部分,例如User.Name,它将在以下部分更新:user = value;,但不在BindableProperty中。
我有办法解决吗还是我做错了什么?谢谢。

khbbv19g

khbbv19g1#

您可以尝试为User实现INotifyPropertyChanged
请参考以下代码:

public class User : INotifyPropertyChanged
{

    private string name;
    public string Name
    {
        get { return this.name; }

        set
        {
            if (value != this.name)
            {
                this.name = value;
                NotifyPropertyChanged(nameof(Name));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String info)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}

相关问题