我有一个 Customer
类,我希望在用户更改 Customer.CityInfo
属性的值时收到通知。
public class City
{
public long Id {get;set;}
public string Code {get;set;}
}
public class Customer
{
private City cityInfo;
private string name;
public long Id { get; set; }
public bool IsCityModified { get; set;}
public bool IsCustomerNameModified { get; set; }
public string Name
{
get{ return name;}
set
{
if(name!=value)
{
IsCustomerNameModified=true; }name=value;
}
}
}
public City CityInfo
{
get
{
if(cityInfo==null)
{
cityInfo=new City();
}
return cityInfo;
}
set{
if(this.cityInfo!=value)
{
IsCityModified =true;
}
this.cityInfo=value;
}
}
}
public ActionResult Save()
{
Customer customer=this.currentCustomerSession;
if(TryUpdateModel<Customer>(customer)){
UpdateModel<Customer>(customer)
}
if(customer.IsCustomerNameModified ){
//I am able to detect whether the customerName value has been changed in the frontend.
}
if(customer.IsCityModified){
//I am not able to detect whether the city value has been changed in the frontend.
}
}
如果客户名称自值类型以来发生更改,我可以将标志 (IsCustomerNameModified) 设置为 true。但无法检测到引用类型中所做的更改。
有人可以帮忙吗?
最佳答案
此类问题通常通过更改通知系统来处理。参见这篇文章:How to: Implement Property Change Notification
片段:
public string PersonName
{
get { return name; }
set
{
name = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("PersonName");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
使用此模式将帮助您避免设置标志或其他此类阴谋。
关于c# - C#中如何检测Property值(ReferenceType属性)是否改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15639700/