Search This Blog

Wednesday, July 20, 2011

Simple command in MVVM model, Silverlight, C#

MVVM model:

  • Model - behaviour and data management
  • View - renders model into UI
  • ViewModel - "model of the view"; data binding between view and model;

This example shows how to create a button with an event "Save" bound to it in MVVM model.

In application's shell (MainPage.xaml) we define UpperPanelView resource and insert the body of UpperPanelView.

MainPage.xaml:

<UserControl x:Class="SilverlightMVVM.MainPage"
    ....
    xmlns:basicviews="clr-namespace:SilverlightMVVM.Views">
    <UserControl.Resources>
        <basicviews:UpperPanelView x:Key="UpperPanelView"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <basicviews:UpperPanelView Grid.Row="1" DataContext="{Binding Source={StaticResource UpperPanelView}}"/>
    </Grid>
</UserControl>

UpperPanelView has a button with a command Save bound to UpperPanelView.Save property.

UpperPanelView.xaml:

<UserControl x:Class="SilverlightMVVM.Views.UpperPanelView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="150" d:DesignWidth="402" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:Label Height="28" HorizontalAlignment="Center" Margin="42,12,54,0" Name="label1" VerticalAlignment="Top" Width="306" Content="Upper panel" FontSize="20" FontWeight="Bold" />
        <Button Content="Save" Height="23" HorizontalAlignment="Center" Margin="159,59,169,0" Name="saveButton" VerticalAlignment="Top" Width="75"
                Command="{Binding Save}" CommandParameter="{Binding ElementName=listImages, Path=SelectedItem}"/>
    </Grid>
</UserControl>

UpperPanelView.xaml.cs hold the Save property of type SaveCommand. We have bound button click property to this event earlier.

UpperPanelView.xaml.cs:

public partial class UpperPanelView : UserControl
{
    public UpperPanelView()
    {
        InitializeComponent();
    }


    //Commands
    private SaveCommand _saveCommand;
    public SaveCommand Save
    {
        get
        {
            if (_saveCommand == null)
                _saveCommand = new SaveCommand(this);
            return _saveCommand;
        }
    }
}


SaveCommand implements ICommand interface and so has the implementation of the Save command.


SaveCommand.cs:

public class SaveCommand : ICommand
    {
        private UpperPanelView _viewModel;

        public SaveCommand(UpperPanelView viewModel)
        {
            _viewModel = viewModel;
        }


        public bool CanExecute(object parameter)
        {
            //return (_viewModel.SelectedCapture != null) ? true : false;
            return true;
        }

        public void Execute(object parameter)
        {
            MessageBox.Show("Ala ma kota");
        }

        public event EventHandler CanExecuteChanged;

        protected virtual void OnCanExecuteChanged(EventArgs e)
        {
            var canExecuteChanged = CanExecuteChanged;

            if (canExecuteChanged != null)
                canExecuteChanged(this, e);
        }
    }

============================================

Another example:

MessageBrowserView.xaml
------------------------
<Button Content="A" Command="{Binding MenuItemClickCommand}"></Button>

MessageBrowserView.xaml.cs
----------------------------
public MessageBrowserView(MessageBrowserViewModel viewModel)
{
  DataContext = viewModel;
  InitializeComponent();
}

MessageBrowserViewModel.cs
---------------------------

public MessageBrowserViewModel()
{
MenuItemClickCommand = new ActionCommand(MenuItemClick);
}

/// <summary>
/// Komenda odpowiadająca na kliknięcie w Menu
/// </summary>
public ICommand MenuItemClickCommand { get; private set; }

private void MenuItemClick()
{
     MessageBox.Show("AAAA");
}

2 comments:

  1. Remember to always use the Command property (and CommandParameter if required) NOT the Click property.
    Click property won't work in this way.

    ReplyDelete

If you like this post, please leave a comment :)