我有一个实体,例如客户继承自IEditableObject
,与描述here:
public class Customer : IEditableObject
{
...
private Boolean backupAvailable = false;
private ThisObject backupData;
public void BeginEdit()
{
if (!backupAvailable)
{
this.backupData.Name = this.Name;
backupAvailable = true;
}
}
public void CancelEdit()
{
if (backupAvailable)
{
this.Name = this.backupData.Name;
backupAvailable = false;
}
}
public void EndEdit()
{
if (backupAvailable)
{
backupData = new ThisObject();
backupAvailable = false;
}
}
}
在我的UI类中,我有一个BindingSource
,其中所有控件都绑定到,2个按钮"更改"和"取消":
BindingSource BSCustomer;
private void buttonChange_Click(object sender, EventArgs e)
{
...
((Customer)BSCustomer.Current).BeginEdit();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
...
((Customer)BSCustomer.Current).CancelEdit();
}
这很好用。
但是现在我已经检测到BeginEdit()
不仅从我的显式调用中被调用,而且从许多其他代码中调用,例如:
BSCustomer.AllowNew = true;
或
BSCustomer.AddNew();
或
BSCustomer.IndexOf();
当我现在点击按钮"更改"时,backupAvailable
已经设置了错误的值。当我点击"取消"写回错误的值。
是否有可能阻止此调用?或者我可以在BeginEdit()
来电来源不同吗?
答案 0 :(得分:1)
只需删除:IEditableObject
即可。如果不这样做,BeginEdit()
只会在手动调用时调用。
Ivan的所有学分。
答案 1 :(得分:0)
我也不得不处理这种情况。谢谢伊万,他们帮助解决了这个问题。 结果,我用 ICloneable 做了这样的事情。
public class Customer : ICloneable
{
struct ThisObject
{
internal string guid;
internal string name;
}
private Boolean backupAvailable = false;
private ThisObject backupData;
private ThisObject currentData;
public void BeginEdit()
{
if (!backupAvailable)
{
var tempCustomer = (Customer)this.Clone();
this.backupData = tempCustomer.currentData;
backupAvailable = true;
}
}
public void CancelEdit()
{
if (backupAvailable)
{
this.currentData = backupData;
backupAvailable = false;
}
}
public void EndEdit()
{
if (backupAvailable)
{
backupData = new ThisObject();
backupAvailable = false;
}
}
public Customer() : base()
{
this.currentData = new ThisObject();
this.currentData.guid = Guid.NewGuid().ToString();
this.currentData.name = string.Empty;
}
public string GUID
{
get { return this.currentData.guid; }
set { this.currentData.guid = value; }
}
public string Name
{
get { return this.currentData.name; }
set { this.currentData.name = value; }
}
public object Clone()
{
return (Customer)this.MemberwiseClone();
}
}
...
private void buttonChange_Click(object sender, EventArgs e)
{
...
((Customer)BSCustomer.Current).BeginEdit();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
...
((Customer)BSCustomer.Current).CancelEdit();
}