开发者

Value Object and View Model Property

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜