MVVM in Windows 8 using GridView Part 1.


There will be two parts to this article. First we will talk about the MVVM pattern in general and how its implemented in Windows 8 and then we will specify it for GridView .

MVVM and MVC…,hows it related ?

Without going in to much detail.I am going to write

  • Model = what it is.
  • View = what it looks like.
  • Controller = what it does.

MVVM – The controller is replaced with a view model. the view model sits below the UI layer. The view model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The view model pulls its data from the model(s) below.The key thing to remember is that you have one and only one ViewModel per view. The view model communicates with the model (business logic, services whatever below it).

Now lets start with the Model .I will just put a boiler plate code and you can reuse it for your good.The model is the actual data that is stored

  class Model : INotifyPropertyChanged
    {

        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; OnPropertyChanged("Title"); }
        }
        private int demoValue;

        public int DemoValue
        {
            get { return demoValue; }

            set { demoValue = value; OnPropertyChanged("Year"); }
        }
public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
}

Now for the Model View

 class MovieViewModel : INotifyPropertyChanged
    {
private List<Model> modelList;

        public  List<Model> ModelList
        {
            get { return modelList;}
            set { 
                modelList= value;
                OnPropertyChanged("ModelList");
            }
        }
private RelayCommand _showDataCommand;

        public ICommand ShowDataCommand
        {
            get
            {
                if (_showDataCommand; == null)
                {
                    _showDataCommand= new RelayCommand(
                        param => getMoviePoster(),
                        param => (true),this

                    );
                }
                return _showDataCommand;
            }

public async void saveMoviePoster()
        {
            Model a = new Model();
            a.Title = "Hello";
            a.DemoValue = 1;
            Model a1 = new Model();
            a1.Title = "World";
            a1.DemoValue = 2;
            List<Model> temp = new List<Model>();
            temp.Add(a);
            temp.Add(a1);
            ModelList= temp;
      }
public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        }

}

The RelayCommand class

class RelayCommand:ICommand
    {
        private ViewModel _ViewModel;
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
            this._ViewMode=_ViewModel;
        }

        public bool CanExecute(object parameter)
        {
            return true;
            //if no net connection return false
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
                  _execute(""); 
            }

        }

Finally the View

<DataTemplate x:Key="StandardItemTemplate">
            <StackPanel Orientation="Vertical" Width="350" Height="350">

                <TextBlock Text="{Binding Title}" TextWrapping="Wrap" 
  HorizontalAlignment="Stretch" Margin="5,5,5,5" FontSize="13"/>
                <TextBlock Text="{Binding Value}" TextWrapping="Wrap"
 FontSize="11" HorizontalAlignment="Stretch" Margin="5,5,5,5"/>

            </StackPanel>
        </DataTemplate>

 <GridView x:Name="gv_view" ItemsSource="{Binding MoviesList}"
 ItemTemplate="{StaticResource StandardItemTemplate}"   />
 <Button x:Name="btn_showData" Command="{Binding ShowDataCommand}"  Content="show" />

 

Now the code behind the View ,that is mainpage.xaml.cs

public sealed partial class MainPage : Page
    {
        ViewModel _ViewModel;
        public MainPage()
        {
            _ViewModel = new ViewModel();
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            gv_view.DataContext = _ViewModel;  

        }
}

 

I will explain the flow in my next post.Till then feel free to use my code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s