Paul
Paul

Reputation: 3273

Adding custom property to object using MVVM

I am new to MVVM and Silverlight

I have managed to get an example Silverlight application up and running

I return the contents of a table - tblClip into my model (Entity Framework) and an associated object Clip.

Now I have a field on my Clip called Size. This is an integer which I want to increase by 5x

What is the correct approach to do this and still keep to the pattern?

1) Add a new property such as ModifiedSize on the model and populate it (although not sure where) I assume I would need to decorate it as a DataMember to get it back to the client 2) In the view model, once I have obtained the data from the service agent, go through the clips increasing the size 3) Something else...?

I do not need to save the objects back to the database.

Paul

Upvotes: 0

Views: 141

Answers (1)

kenwarner
kenwarner

Reputation: 29120

UI specific properties belong on the ViewModel. For example, this is one way you could do it

public class ClipViewModel
{
    private int _size;

    public int Size
    {
        get { return _size; }
        set
        {
            _size = value;
            NotifyPropertyChanged("Size");
        }
    }

    public int ModifiedSize
    {
        get { return Size * 5; }
        set
        {
            Size = value / 5;
        }
    }
}

Binding to ModifiedSize in your XAML would then update Size as well as perform INotifyPropertyChanged notifications

The other thing you can do is skip the ModifiedSize property and use a converter

public class ModifiedSizeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        return (int)value * 5;
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        return (int)value / 5;
    }
}

and then bind to Size with the converter

<Slider Value="{Binding Path=Size, Converter={StaticResource modifiedSizeConverter}}" />

Upvotes: 1

Related Questions