I am working on a solution that used DDD for architecture. I have a property in my ViewModel which points to a ValueObject, the view model also implements INotifyPropertyChanged interface. The value of the ValueObject will change as a user enters data on the front end. The p开发者_如何学Pythonroblem I am running into is the value object is suppose to be immutable. How can I work around this issue? Thank you in advance.
If you can edit something, then there must be a mutable container for the immutable value. Therefore, your viewmodel should act on the mutable container rather than on the immutable value directly.
An integer is an example of such an immutable value object: the Int32
type does not have any members that allow you to change the state of the object. You can only replace an integer, not change it. So a view model for an integer would look like this:
public MutableIntegerViewModel
{
private readonly mutableInteger;
public MutableIntegerViewModel(MutableInteger mutableInteger)
{
this.mutableInteger = mutableInteger;
}
public string DisplayText
{
get
{
return this.mutableInteger.Value.ToString(
CultureInfo.CurrentCulture);
}
set
{
this.mutableInteger.Value =
Int32.Parse(value, CultureInfo.CurrentCulture);
}
}
}
Where MutableInteger
is just this:
public class MutableInteger
{
public int Value { get; set; }
}
I've omitted error handling and change notification here, but hopefully you get the idea.
Also note this example is not really different from the typical example of a Customer
class with a FirstName
and a LastName
. Strings are also immutable, so again we have a mutable container for immutable values.
精彩评论