我是从这样的对象绑定属性:
ViewModel :
public class VieModel
{
public Model MyModel
{
get
{
return myModel;
}
set
{
myModel = value;
}
}
private Model myModel
}
模型:
public class Model
{
public string Name { get; set;}
public string Info { get; set;}
public string MoreInfo { get; set;}
}
查看:
<TextBox Text="{Binding MyModel.Name, Mode=TwoWay, Mode=TwoWay, UpdateSourceTrigger=LostFocus }" />
<TextBox Text="{Binding MyModel.Info, Mode=TwoWay, UpdateSourceTrigger=LostFocus }" />
<TextBox Text="{Binding MyModel.MoreInfo, Mode=TwoWay, UpdateSourceTrigger=LostFocus }" />
一切正常工作,但是当MyModel
更改时,我想检查是否有任何属性更改,以便我可以先保存用户。
所以我的第一个想法是添加一个布尔值,该布尔值在任何更改上都变为true,以便我可以在MyModel
的设置中检查。但是目前,当我更改属性时即使在后台更改属性时,我都没有收到通知。
总而言之,因为MyModel
并没有真正改变。但是如何检测任何属性的更改?
预先感谢!:)
答案:
检查当前的MyModel
是否与您需要存储该对象的副本的旧 CC_5是否相同,以便能够按照Bijington的描述进行比较
为此,您可以手动执行或使用二进制序列化器,以便您可以克隆暴民。
手动:
public class Model
{
public string Name { get; set;}
public string Info { get; set;}
public string MoreInfo { get; set;}
public static Model Clone(Model obj)
{
Model newModel = new Model();
newModel.Name = obj.Name;
newModel.Info = obj.Info;
newModel.MoreInfo = obj.MoreInfo;
return newModel;
}
}
binaryFormatter.Serialize :
您需要 Model
中使用的每个具有[Serializable]
属性。
[Serializable]
public class Model
{
public string Name { get; set;}
public string Info { get; set;}
public string MoreInfo { get; set;}
public SecondModel SecondOne { get; set;}
public static Model Clone(Model obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
}
[Serializable]
public class SecondModel
{
public string SecondName { get; set;}
public string SecondInfo { get; set;}
public string SecondMoreInfo { get; set;}
}
我从初始评论中略微改变了我的方法。我选择的选项不是实现IComparer
是覆盖Equals
方法。
public class Model
{
public string Name { get; set; }
public string Info { get; set; }
public string MoreInfo { get; set; }
public override bool Equals(object obj)
{
if (obj is Model model)
{
return string.Equals(this.Name, model.Name, StringComparison.Ordinal);
// && Add your other property comparisons here...;
}
return false;
}
public override int GetHashCode()
{
// You really should provide your implementation here:
return base.GetHashCode();
}
}
然后 public class VieModel
{
private Model myModel;
public Model MyModel
{
get
{
return myModel;
}
set
{
if (myModel?.Equals(value) != true)
{
// The model has changed so you can perform what you want here...
myModel = value;
}
}
}
}