Click here to Skip to main content
15,886,019 members
Articles / Desktop Programming / WPF

WPF/MVVM Quick Start Tutorial

Rate me:
Please Sign up or sign in to vote.
4.92/5 (699 votes)
10 Oct 2012CPOL11 min read 1.7M   61K   651  
A quick example of MVVM in WPF
using System.Collections.ObjectModel;
using System.Windows.Input;
using MicroMvvm;

namespace Example5
{
    class AlbumViewModel
    {
        #region Members
        private SongDatabase _database = new SongDatabase();
        ObservableCollection<Song> _songs = new ObservableCollection<Song>();
        #endregion

        #region Properties
        public ObservableCollection<Song> Songs
        {
            get
            {
                return _songs;
            }
            set
            {
                _songs = value;
            }
        }
        #endregion

        #region Construction
        public AlbumViewModel()
        {
            for (int i = 0; i < 3; ++i)
            {
                _songs.Add(new Song { ArtistName = _database.GetRandomArtistName, SongTitle = _database.GetRandomSongTitle });
            }
        }
        #endregion

        #region Commands
        void UpdateAlbumArtistsExecute()
        {
            if (_songs == null)
                return;

            foreach (var song in _songs)
            {
                song.ArtistName = _database.GetRandomArtistName;
            }
        }

        bool CanUpdateAlbumArtistsExecute()
        {
            return true;
        }

        public ICommand UpdateAlbumArtists { get { return new RelayCommand(UpdateAlbumArtistsExecute, CanUpdateAlbumArtistsExecute); } }


        void AddAlbumArtistExecute()
        {
            if (_songs == null)
                return;

            _songs.Add(new Song { ArtistName = _database.GetRandomArtistName, SongTitle = _database.GetRandomSongTitle });
        }

        bool CanAddAlbumArtistExecute()
        {
            return true;
        }

        public ICommand AddAlbumArtist { get { return new RelayCommand(AddAlbumArtistExecute, CanAddAlbumArtistExecute); } }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
Jack of all trades.

Comments and Discussions