This project is read-only.

Quick Examples

A simple ViewModel

The following code illustrates a very simple ViewModel, using the SpiritMVVM library:

using SpiritMVVM.ViewModels;

namespace Example
{
    public class MyViewModel : ViewModelBase
    {
        private string _myString = "Hello, world";
        public string MyString
        {
            get { return _myString; }
            set { Set(ref _myString, value); }
        }
    }
}

As you can see, no "magic strings" are required to raise the PropertyChanged event. SpiritMVVM makes use of the CallerMemberName attribute, introduced in .NET 4.5 and above, to avoid unnecessary (and bug-prone) string syntax. When spread over the course of many properties and many ViewModels, this saves you lots of extra 'framework' coding. Your code can get to the point, without any extra fluff.

A ViewModel which wraps a Model

Of course, the above code only works if you have a field contained within the ViewModel itself; what if you want to do the same thing, with an underlying model?

As it turns out, SpiritMVVM makes it easy to wrap Model properties from within a ViewModel.

using SpiritMVVM.Utils;
using SpiritMVVM.ViewModels;

namespace Example
{
    public class Model
    {
        public int Value { get; set; }
    }

    // The generic ViewModel<T> class provides a property
    // "Model" for accessing the underlying Model instance
    public class ViewModel : ViewModelBase<Model>
    {
        public ViewModel()
        {
            //Initialize the accessor with lambda expressions,
            //Getting and Setting the underlying Model value.
            _wrapperValueAccessor = new Accessor<int>(
                () => this.Model.Value,
                (x) => this.Model.Value = x);
        }

        private Accessor<int> _wrapperValueAccessor;
        public int WrapperValue
        {
            get { return _wrapperValueAccessor.Value; }
            set { Set(_wrapperValueAccessor, value); }
        }
    }
}

A Custom Reaction when a Property Changes


using SpiritMVVM.ViewModels;

namespace Example
{
    public class MyViewModel : ViewModelBase
    {
        private string _myString = "Hello, world";
        public string MyString
        {
            get { return _myString; }
            set 
            {
                Set(ref _myString, value, (oldVal, newVal) =>
                {
                    // This lambda method is called only when
                    // the property value is actually changed.
                    // Users can use this block to perform custom
                    // logic (such as subscribing/unsubscribing to events,
                    // or pushing data to an underlying model).
                    // The "PropertyChanged" event does NOT need
                    // to be raised here - it will be done automatically.
                });
            }
        }
    }
}

Last edited Oct 27, 2013 at 5:04 PM by btowntkd, version 4

Comments

No comments yet.