Tuesday, 3 November 2015

Simple example similar to MVVM layout

Today let us discuss  about a simple example in windows phone 8.1 apps with MVVM layout.

MVVM is mainly to separate the user interface ie view and the view model. This can be achieved by data binding. There are many classes used to maintain the standards of MVVM flow. Most of the developers use this MVVM architecture to design the applications mainly for some reasons. The code can be reusable. The unit testing is very easy if an application follows MVVM. Updates can be easily managed in the code.

It is possible to show a message dialog in a button click. This is done by generating a click event. But with out this click event we can display the message dialog by using command interfaces.

Similar to this example the developers follow this kind of models and views.

Drag and drop a button to the designer in windows phone 8.1 MainPage.xaml

Create a new class file and name it.

Now add the below code to the class file

In the below code CommandEx is the name of my class and ICommand is the interface. When we click on the blue dotted line down to the text we can implement the interface in our code. It adds CanExecute and Execute method with EventHandler.


class CommandEx:ICommand
    {
        public bool CanExecute(object parameter)
        {
            if (parameter != null)
            {
                return true;
            }
            else
                return false;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            var msd = new MessageDialog(parameter.ToString()).ShowAsync();
        }
    }


So with the help of binding the code in the command will be executed.


    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    
    <Page.Resources>
        <local:CommandEx x:Key="ll"/>
    </Page.Resources>

    <Grid>
        <Button Content="Click"
                HorizontalAlignment="Left"
                Command="{StaticResource ll}"
                CommandParameter="Hello World"
                Margin="60,164,0,0"
                VerticalAlignment="Top"
                Height="42"
                Width="158"/>

    </Grid>

In the XAML code add page resource to use the class (CommandEx). Define a key and use that key in the button, binding to the command. Here the command parameter is from the execute method defined in the class.

No comments:

Post a Comment