我找到了一个很好的类型验证代码示例:
public class StringViewModel : ViewModelBase, IComparable
{
private string _value;
private string _originalValue;
public StringViewModel(string value)
{
_value = value;
_originalValue = value;
}
// Der eigentliche Wert.
public string Value
{
get { return _value; }
set
{
if (value != _value)
{
_value = value;
RaisePropertyChanged("Value");
HasChanges = _value != _originalValue && !(string.IsNullOrEmpty(_value) && string.IsNullOrEmpty(_originalValue));
}
}
}
public override void AcceptChanges()
{
_originalValue = _value;
HasChanges = false;
HasError = false;
}
public override void UndoChanges()
{
Value = _originalValue;
HasError = false;
}
// Muss implementiert werden, damit die Sortierung im CollectionView funktioniert.
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (object.ReferenceEquals(this, obj)) return 0;
StringViewModel other = obj as StringViewModel;
return string.Compare(this._value, other._value);
}
public override string ToString()
{
return _value;
}
}
现在我想让它更通用,所以我需要在运行时创建以下 2 个值:
private T? _value;
private T? _originalValue;
因为我想做类似的事情:
public class ItemModel : IComparable, INotifyEXTEND
{
private ??? _value;
private ??? _originalValue;
public ItemModel(string value)
{
_value = value;
_originalValue = value;
}
public ??? Value
{
get { return _value; }
set
{
if (value != _value)
{
_value = value;
RaisePropertyChanged("Value");
HasChanges = _value != _originalValue && !(string.IsNullOrEmpty(_value) && string.IsNullOrEmpty(_originalValue));
}
}
}
public override void AcceptChanges()
{
_originalValue = _value;
HasChanges = false;
HasError = false;
}
public override void UndoChanges()
{
Value = _originalValue;
HasError = false;
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (object.ReferenceEquals(this, obj)) return 0;
??? other = obj as ???;
return string.Compare(this._value, other._value);
}
public override string ToString()
{
return _value;
}
}
所以我可以这样使用它:
public class PersonViewModel : ViewModelBase
{
private Person _person;
private ItemModel _lastname;
private ItemModel _birthdate;
private bool _isNew;
// Otherstuff
}
关于如何做到这一点的任何建议?(一些示例代码片段或链接会很好)