我有一个可观察的供应商集合,我想将它们加载到 GridView 中,然后让用户编辑供应商的任何相关信息。我的问题是我不确定如何为供应商(模型)上可以更改的每个属性实现 IsDirty 字段。我有这样创建的 IsDirty 位
#region SupplierID
private int _SupplierID;
public int SupplierID
{
get
{
return _SupplierID;
}
set
{
if (_SupplierID != value)
{
_SupplierID = value;
OnPropertyChanged("SupplierID");
}
}
}
#endregion
#region Address
private string _Address;
public string Address
{
get
{
return _Address;
}
set
{
if (_Address != value)
{
_Address = value;
IsDirtyAddress = true;
OnPropertyChanged("Address");
}
}
}
public bool IsDirtyAddress{ get; set; }
#endregion
#region City
private string _City;
public string City
{
get
{
return _City;
}
set
{
if (_City != value)
{
_City = value;
IsDirtyCity = true;
OnPropertyChanged("City");
}
}
}
public bool IsDirtyCity { get; set; }
#endregion
#region State
private string _State;
public string State
{
get
{
return _State;
}
set
{
if (_State != value)
{
_State = value;
IsDirtyState = true;
OnPropertyChanged("State");
}
}
}
public bool IsDirtyState { get; set; }
#endregion
#region Zip
private string _Zip;
public string Zip
{
get
{
return _Zip;
}
set
{
if (_Zip != value)
{
_Zip = value;
IsDirtyZip = true;
OnPropertyChanged("Zip");
}
}
}
public bool IsDirtyZip { get; set; }
#endregion
问题是,当我构建供应商列表 (ViewModel) 时,我实际上最终将 IsDirty 位设置为 true。在不将 IsDirty 位设置为 true 的情况下,在创建供应商时设置我的地址、城市、州、 zip 的最佳方法是什么?我的模型中需要初始化函数吗?
for (int i = 0; i < dtSupplier.Rows.Count; i++)
{
Supplier s = new Supplier()
{
SupplierID = Convert.ToInt32(dtSupplier.Rows[i]["SupplierID"].ToString()),
Address = dtSupplier.Rows[i]["Address"].ToString(),
City = dtSupplier.Rows[i]["City"].ToString(),
State = dtSupplier.Rows[i]["State"].ToString(),
Zip = dtSupplier.Rows[i]["Zip"].ToString()
};
Suppliers.Add(s);
}
也许我正在以错误的方式处理整个 IsDirty 方法。我只想知道实际更改了哪些值,因此我的 SQL 更新语句将仅在用户保存时包含更改的值。谢谢!
最佳答案
你需要做几件事:
Loading
.在加载 ViewModel 时,设置 Loading
属性为真。完成加载后,将其设置为 false。 Loading
并且不要设置IsDirty
标志。此外,即使未处于加载状态,也要将这些值与模型中的值进行比较,看看它们是否相同。 nameof
(见下面我的例子)。 IsDirty
标志,所以将 setter 设为私有(private)。 这是一个假设的例子:
public class Model
{
public string Name { get; set; }
}
public class ViewModel : INotifyPropertyChanged
{
private readonly Model model;
public ViewModel(Model model)
{
this.model = model;
}
public bool Loading { get; set; }
public bool IsDirtyName { get; private set; }
private string name;
public string Name
{
get
{
return this.name;
}
set
{
if (this.Loading)
{
this.name = value;
return;
}
if (this.model.Name != value)
{
IsDirtyName = true;
OnPropertyChanged(nameof(Name));
}
}
}
private void OnPropertyChanged(string propertyName)
{
// ...
}
public event PropertyChangedEventHandler PropertyChanged;
}
如果你注意上面的设计,你甚至不需要所有这些
IsDirty
标志和 IsLoading
等等。实际上,您可以在保存期间调用 ViewModel 中的一种方法,并要求它检查并返回所有已更改的属性。 ViewModel 会将自己的属性与 Model 属性进行比较并返回一个字典。有很多方法可以实现你想要的。
关于c# - 对我的模型上的属性实现 IsDirty (WPF MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47518863/