给定如下所示的类:

public class LoginInfo
{
    public int UserId;
    public string Username;
}


和另一类

public class OtherClass
{
    public static LoginInfo Info
    {
        get
        {
            return SessionBll.GetLoginInfo(someInt);
        }
        set
        {
            SessionBll.UpdateLoginInfo(value, someInt);
        }
    }
}


并为此:

OtherClass.LoginInfo.Username = "BillyBob";


LoginInfo的属性更改时,如何调用LoginInfo设置器?我知道我可以做:

LoginInfo info = OtherClass.LoginInfo;
info.Username = "BillyBob";
OtherClass.LoginInfo = info;


但我想在没有这三行的情况下执行此操作。我希望它是自动的

谢谢

最终在LoginInfo类中订阅了该事件

最佳答案

尝试对您的班级进行以下修改

public class LoginInfo : INotifyPropertyChanged
{
    private int _userID;
    private string _UserName;

    public event PropertyChangedEventHandler PropertyChanged;

    public int UserId
    {
        get { return this._userID; }
        set
        {
            if (value != this._userID)
            {
                this._userID = value;
                NotifyPropertyChanged("UserID");
            }
        }
    }

    public string Username
    {
        get { return this._UserName; }
        set
        {
            if (value != this._UserName)
            {
                this._UserName = value;
                NotifyPropertyChanged("UserName");
            }
        }
    }

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}


然后,在另一个类中,您需要引用loginfo类并订阅PropertyChangedEvent。

_privateLogInfo.PropertyChanged += new PropertyChangedEventHandler(methodToBeCalledToHandleChanges);


然后处理methodToBeCalledToHandleChanges中的所有更改。

10-06 12:04