Given a class like below:
public class LoginInfo
{
public int UserId;
public string Username;
}
and another class
public class OtherClass
{
public static LoginInfo Info
{
get
{
return SessionBll.GetLoginInfo(someInt);
}
set
{
SessionBll.UpdateLoginIn开发者_StackOverflow社区fo(value, someInt);
}
}
}
and given this:
OtherClass.LoginInfo.Username = "BillyBob";
How can I call the LoginInfo
setter when a property of LoginInfo
changes? I know I can do:
LoginInfo info = OtherClass.LoginInfo;
info.Username = "BillyBob";
OtherClass.LoginInfo = info;
but I want to do this without these three lines. I want it to be automatic
Thanks
Ended up subscribing to the event in the LoginInfo class
There are many different approaches. The most straightforward is to have LoginInfo
implement INotifyPropertyChanged
and have OtherClass
subscribe to the PropertyChanged
event and then you can have that event handler call the setter as needed.
No matter what, you have to do some work to get this wired up correctly.
Try the following amendments to your class
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));
}
}
}
Then in your other class you need to have a reference to the loginfo class and subscribe to the PropertyChangedEvent.
_privateLogInfo.PropertyChanged += new PropertyChangedEventHandler(methodToBeCalledToHandleChanges);
Then handle any changes in methodToBeCalledToHandleChanges.
精彩评论