DeutschEnglish

Dec 18

[MVVMbasics] MVVMbasics and the UI thread

Notice

All blog posts with a title that starts with [MVVMbasics] are related to the MVVMbasics framework. If you are only interested in my regular blog posts and not in MVVMbasics, ignore these. To list all articles covering MVVMbasics, go to http://mvvmbasics.mobilemotion.eu/documentation!

In .NET front end applications, all code that accesses user interface elements needs to be executed on the main UI thread. Business logic, however, might run on separate threads – for example, network or NFC communication callbacks are usually executed on separate threads, as well as long-running business logic that is typically assigned to a separate thread intentionally in order to not block the graphical user interface.

If such code blocks shall be able to update the user interface, the statements that actually access UI elements in order to update them need to be explicitly assigned back to the UI thread. All common platforms (such as Windows Store, Windows Phone, WPF, etc.) feature some dispatcher object that takes care of scheduling certain statements to be executed on the UI thread: As developer, you don’t need to find the actual UI thread and assign code statements to this thread, instead you simply instruct the dispatcher to do that for you.

Unfortunately the dispatcher pattern is realized in different ways on those platforms – they all have their own implementation of dispatcher objects that reside within different namespaces and offer varying methods. When developing applications that target multiple platforms, there is no common way of accessing a single dispatcher object from within cross-platforms Viewmodels – however, business logic is typically executed on the MVVM Viewmodel layer, so platform-dependent implementations are not a useful alternative either since this implies that business logic is implemented redundantly for each target platform.

This is where the smart dispatcher that is integrated in MVVMbasics version 2.1 (and higher) comes into play: All Viewmodels derived from MVVMbasics‘s BaseViewmodel class provide the new RunOnMainThread(Action a) method. This method checks whether a certain action would (if simply executed) run on some separate thread that does not have access to the UI thread, and if so instructs the dispatcher to assign it to the UI thread.

Using the MVVM pattern, direct access to UI elements is typically replaced by data binding. This means, only the PropertyChanged event that informs the UI about changes in the underlying data needs to be raised on the UI thread. When using the MVVMbasics Set method to update a data binding property from within a Viewmodel, from version 2.1 on the PropertyChanged event raising mechanism is automatically invoked using the dispatcher if currently not running on the UI thread, which means that it is not necessary to wrap property assignments in the above-mentioned RunOnMainThread method – this is done automatically by the MVVMbasics framework!

Permanent link to this article: http://www.mobilemotion.eu/?p=1342&lang=en

Dec 16

New version MVVMbasics 2.1 available

MVVMbasics 2.1 features a common way for dependency injection of the global service locator into both Viewmodels and Services, as well as a smart UI dispatcher. Also available is a new version of the Visual Studio project templates which now handle the Windows Phone 8.1 back button correctly.                          

Permanent link to this article: http://mvvmbasics.mobilemotion.eu

Dec 10

Crashing the visual XAML editor

I’m back from vacation and just stumbled across a small problem in the WinRT framework. In an earlier blog post, I described how to be notified when a Windows Store App is "minimized" (for example because the user presses the Windows button, or because another app becomes active) by subscribing to the current window’s VisibilityChanged event. When implementing this solution, you’ll probably end up with a line similar to the following in a page’s constructor:

Window.Current.VisibilityChanged += OnVisibilityChanged;

…and the OnVisibilityChanged event handler’s implementation somewhere else. The problem is, when opening this page in Visual Studio’s embedded XAML editor (you know, the one that tries to visualize the page’s content), in some cases you’ll just encounter an Cannot create an instance of "XyzView"… instead of the actual page content:

XAML editor error

 
 
 
 
 
 
 
 

The easiest workaround for this problem is to ensure that the VisibilityChanged event handler is not registered when viewing the page from within Visual Studio, but only at runtime. This can be done by checking whether the App is running in design mode using the DesignMode.DesignModeEnabled flag:

if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
	Window.Current.VisibilityChanged += OnVisibilityChanged;

Now you should be able to use the visual XAML editor as usual!

Permanent link to this article: http://www.mobilemotion.eu/?p=1329&lang=en

Nov 18

The very basics of MVVM #6: Command and conquer

As an extension to the first five parts of this series of articles, I promised to add one final blog post explaining Command Binding in .NET in detail.

As I mentioned already, the .NET framework containsa generic ICommand interface, but it leaves the implementation of the actual commands to us developers. There are two ways of implementing the ICommand interface: You can either create a distinct Command class for each command in your application (meaning, for each single Viewmodel functionality that shall be triggered from within the View). I personally prefer to create only one generic Command class that can be initialized with different parameters to reflect the different functionalities.

The simplest possible Command

When looking at the ICommand interface, you’ll discover that it only defines only three members: Two methods Execute and CanExecute and one CanExecuteChanged event. For the simplest possible Command, the last two are not even necessary, let’s just concentrate on the Execute method:

When assigning a Command object to any user control in the View using the {Binding SomeCommand} syntax, as soon as the user performs this control’s default event (e.g., clicks a Button), the Command’s Execute method is invoked. This means we need to implement the Execute method in a way that it invokes the desired Viewmodel functionality. We can realize this by passing some delegate to the Command’s constructor, storing this delegate within the Command, and invoke it from within the Execute method:

public class DelegateCommand : ICommand
{
	private readonly Action _action;

	public DelegateCommand(Action action)
	{
		_action = action;
	}

	public void Execute(object parameter)
	{
		_action.Invoke();
	}
}

Within the Viewmodel, any method containing business logic can be passed to this generic DelegateCommand (note that this method can even be marked private):

public sealed class SomeViewmodel : INotifyPropertyChanged
{
	public DelegateCommand DoSomethingCommand { get; set; }
	
	public SomeViewmodel()
	{
		DoSomethingCommand = new DelegateCommand(DoSomething);
	}
	
	private void DoSomething()
	{
		// any business logic is executed here...
	}
}

Adding Command parameters

The .NET MVVM implementation allows passing parameters to Commands, as shown in the following example for a Button control – the button’s command parameter is binding to another control’s attribute, in this case a TextBox‘ text, and this text shall be passed to the command:

<TextBox x:Name="SomeTextBox" />
<Button Command="{Binding DoSomethingCommand}" CommandParameter="{Binding ElementName=SomeTextBox, Path=Text}">Click me</Button>

This is the reason why the ICommand‘s Execute method has one parameter of type object: When invoking an Action that also expects a parameter, we can simply pass on this object:

public class DelegateCommand : ICommand
{
	private readonly Action<object> _action;

	public DelegateCommand(Action<object> action)
	{
		_action = action;
	}

	public void Execute(object parameter)
	{
		_action.Invoke(parameter);
	}
}

The usage within the Viewmodel looks similar – the only difference is that the parameter is passed through to our business logic method, where we can make use of it:

public sealed class SomeViewmodel : INotifyPropertyChanged
{
	public DelegateCommand DoSomethingCommand { get; set; }
	
	public SomeViewmodel()
	{
		DoSomethingCommand = new DelegateCommand(DoSomething);
	}
	
	private void DoSomething(object parameter)
	{
		string input = (string)parameter;
		// any business logic that makes use of the input text is executed here...
	}
}

(Of course, in a real-life generic Command implementation, we’d include both constructors in order to use the Command with both parameterized and parameterless business logic methods.)

Conditional Command execution

Remember our sample to-do-item application?In the CreateViewmodel class, we defined a StoreItemCommand that executes a method which creates a new to-do-item based on a description property, and stores this item in a database. If the user has not entered any text as description, there is no point in creating a to-do-item since it would be empty – so, what if we’d want the button that actually invokes this StoreItem functionality to be active only some text is present within the description text box?

Of course, we could bing the button’s IsEnabled attribute to the TextBoxText attribute, such that the button is disabled if the TextBox is empty. However, this means we’d be adding business logic to the View layer that should rather belong to the Viewmodel layer! (Imagine you’d like to create multiple to-do applications for different platforms, designing individual View classes for each platform but re-using the Viewmodel classes since all Apps should share the same functionality: The dependency of the button’s IsEnabled attribute to the TextBoxText attribute needs to be created redundantly for each platform!)

Instead, a much cleaner solution is to define this dependency on the Viewmodel layer, and instruct the Command that is shall only be executable if the TaskDescription property contains some text! This is where the ICommand‘s CanExecute method and CanExecuteChanged event come into play: In addition to the business logic method we pass a second delegate to the Command’s constructur that describes a condition which must be fulfilled for the Command to be executable. Also this delegate is stored internally, and evaluated whenever the Command’s CanExecute method is executed:

public class GenericCommand : ICommand
{
	private readonly Action<object> _action;

	private readonly Func<object, bool> _condition;

	public GenericCommand(Action<object> action, Func<object, bool> condition)
	{
		_action = action;
		_condition = condition;
	}

	public void Execute(object parameter)
	{
		_action.Invoke(parameter);
	}

	public bool CanExecute(object parameter)
	{
		return _condition.Invoke(parameter);
	}

	public event EventHandler CanExecuteChanged;

	public void RaiseCanExecuteChanged()
	{
		if (CanExecuteChanged != null)
			CanExecuteChanged(this, EventArgs.Empty);
	}
}

The View will automatically call the Command’s CanExecute method to find out whether the Command is allowed to be executed, and adapt the visual display accordingly (e.g., disable or enable the button that is binded to the Command).

In the Viewmodel, we simply pass the condition as second parameter when initializing the Command:

public sealed class SomeViewmodel : INotifyPropertyChanged
{
	private string _taskDescription;
    public string TaskDescription
    {
        get { return _taskDescription; }
        set
        {
            if (!_taskDescription.Equals(value))
            {
                _taskDescription = value;
                RaisePropertyChanged("TaskDescription");
				DoSomethingCommand.RaiseCanExecuteChanged();
            }
        }
    }
		
	public DelegateCommand DoSomethingCommand { get; set; }
	
	public SomeViewmodel()
	{
		DoSomethingCommand = new DelegateCommand(DoSomething, () => !String.IsNullOrEmpty(TaskDescription));
	}
	
	private void DoSomething(object parameter)
	{
		// any business logic that is executed only if the TaskDescription property contains text!
	}
}

Notice that there is one more thing necessary for this dependency to work: Since the DoSomethingCommand depends on the TaskDescription property, the Command needs to be notified whenever this property changes! Therefore I added a call to the Command’s RaiseCanExecuteChanged method in the property’s setter, which is just a short convenience function that raises the Command’s CanExecuteChanged event. The View can register to this event to be notified whenever the Command’s condition needs to be re-evaluated.

There are a few ways to automate this notification (and, in general, enhance this basic generic Command class), but that’s a topic for a separate blog post…

Permanent link to this article: http://www.mobilemotion.eu/?p=1308&lang=en

Nov 08

The very basics of MVVM #5: Intercepting Data Bindings

After having read the first four parts of this series of articles, you should by now know the basic structure of the Model, View, and Viewmodel layers of the MVVM architecture, and that View and Viewmodel classes can communicate via Data Binding.

There exists one limitation of Data Bindings that may lead to problems: The fact that both target and source of a Data Binding need to have the same data type. This means that, for example, we can only bind a string property to a TextBox’ Text attribute, because this one also is of type , but not to its MaxLength attribute. Sounds reasonable – the MaxLength attribute only accepts numbers, so what should it do with some arbitrary text?

There are, however, cases where a binding between different data types is desired. For example, let’s extend the ListPage of our sample to-do application: In the list of all existing to-do items, in addition to each item’s description we’d like to display a small check mark symbol if the item is done (and hide this symbol if not). Let’s first integrate the symbol into the View by using an Image control:

<ListView ItemsSource="{Binding Items}">
	<ListView.ItemTemplate>
		<DataTemplate>
			<StackPanel Orientation="Horizontal">
				<TextBlock Text="{Binding TaskDescription}" />
				<Image Source="done.png" />
			</StackPanel>
		</DataTemplate>
	</ListView.ItemTemplate>
</ListView>

Until now, the symbol is visible for all items, of course. What do we need to do to add interactivity? Fortunately, our Model contains an IsDone flag, so let’s just use this for binding:

<Image Source="done.png" Visibility="{Binding IsDone}" />

Nice try, but this won’t run. A quick check in the MSDN reference shows that the Image control’s Visibility attribute is of type Windows.UI.Xaml.Visibility – we can’t bind this attribute to the bool property as planned!

Of course we could adapt the Model class and change the IsDone property’s type to Windows.UI.Xaml.Visibility, but

  • sematically, this isn’t the cleanest solution (a property named is-done should be set either to true or false, not to Visibility or Collapsed
  • then the Model can not be used in a cross-platform context any more (because the Windows.UI.Xaml.Visibility enumeration only exists in WnRT), and we’d give up one of the biggest advantages of the MVVM architecture
  • we’d not be able to use the IsDone for something else than hiding or showing some user controls – for example, what if in some other View we’d like to enable or disable some command based on this flag?

Instead, the most common way of making such cross-type bindings work is the use of a value converter. Converters intercept Data Bindings and allow us to adapt their content. In our case, we’d like to retrieve the boolean value coming from the Model, convert it into a value of type Windows.UI.Xaml.Visibility, and pass this value on to the View. Such a converter could look similar to the following code snippet:

[ValueConversion(typeof(Visibility), typeof(bool))]
public class BooleanToVisibilityConverter : IValueConverter
{
	public object Convert(object value, Type targetType, object parameter, string language)
	{
		bool input = (bool) value;
		return input ? Visibility.Visible : Visibility.Collapsed;
	}

	public object ConvertBack(object value, Type targetType, object parameter, string language)
	{
		return DependencyProperty.UnsetValue;
	}
}

The ValueConversion attribute reflects both the source and the target type, but it’s not strictly necessary to add this to each converter class (it just helps development tools distinguish the data types involved in the conversion). Each value converter contains two methods (Visual Studio will suggest those two as soon as you make some class inherit from the IValueConverter interface): Convert and ConvertBack. For the moment, let’s focus on the first one:

The Convert method is invoked after the source value has been retrieved from the (View-)Model, and before it is applied to the target control in the View. The source value is being passed as the first parameter (we can ignore the other three parameters for now, as they are rarely used) – we convert it to whatever type we like, and return this target value. By the way, the IValueConverter interface that is shown here for WinRT also exists on the Phone Silverlight and WPF platforms, these versions only differ in the second to fourth parameters to the Convert method but work exactly the same otherwise!

The ConvertBack is only used on two-way-bindings, for example in combination with a TextBox where the user is allows to enter some text, and this text shall be stored within the Viewmodel property. In our case, it will never be invoked since the Visibility will never be changed in the View and needs therefore not be passed back to the (View-)Model. Due to this, we instruct it to return DependencyProperty.UnsetValue since this is the default value for converters that don’t do anything – it will cause the Data Binding to use its default or fallback value.

The only thing left to do is tell our Data Binding to actually use this converter. To do so, we first need to declare it as static resource either in the View class or within App.xaml:

<Application.Resources | Page.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanConverter" />
    <!-- additional converters and other resources follow here... -->
</Application.Resources | Page .Resources>

Now we’re ready to actually reference the converter, this is done by just setting the Data Binding expression’s Converter property:

<Image Source="done.png" Visibility="{Binding IsDone, Converter={StaticResource BooleanConverter}}" />

Value converters can do a lot more than this, and in addition there are other types of converters, but this should be enough to get a basic idea of how the pattern works. If you’re interested in all the fancy things you can do with converters, you might take a look at the series Three things you probably didn’t know about XAML converters: Combining ValueConverters, Passing parameters to ValueConverters, and A better ValueInverter.

This series of articles about the very basics of MVVM continues with part #6 (Command and conquer) discussing Commands in detail.

Permanent link to this article: http://www.mobilemotion.eu/?p=1317&lang=en

Nov 03

The very basics of MVVM #4: Enjoy the View

By now you should have read everything about the basic structure of MVVM in part #1, the contents of the Model layer in part #2, and the Viewmodel layer’s structure in part #3 – so let’s finally make use of all this knowledge and enjoy the View layer!

Each View class generally represents a visual screen that is displayed to the user – as mentioned before, in most cases this is a WPF window, a Windows Phone page, a web page, etc. However, you may also build a window or a page consisting of several Views: For example, if your WPF window contains a large TabControl, each tab item might be realized as separate View. This is especially useful if the various tab items contain very different data and functionality, to separate these functionalities from each other.

In all cases, each View will have its very own Viewmodel. It makes sense to name the Viewmodels after their corresponding View, so in our sample to-do list application we’d have two View classes CreatePage and ListPage (assuming we’re realizing it as Windows Phone or Windows Store App – in case of a WPF application, they would be called CreateWindow and ListWindow, of course). By the way, also the following two code snippets have been created for a Windows Phone app, but can easily be adapted for a WPF application by replacing Page by Window and changing the structure of the namespace declarations at the beginning of the file!

The View classes should only contain what’s necessary to display a nice user interface on the screen – in practice, this means they are built out of user controls, and usually implemented using XAML code. This also means that a View class’ C# code-behind file does not contain too much code, because it won’t contain business logic functions – our two example pages contain no C# code at all, except for the obligatory InitializeComponent() call in the constructor:

public sealed partial class CreatePage : Page
{
	public CreatePage()
	{
		this.InitializeComponent();
	}
}

The CreatePage example

<Page x:Class="App1.Views.CreatePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewmodels="using:App1.Viewmodels">
	
	<Page.DataContext>
		<viewmodels:CreateViewmodel />
	</Page.DataContext>

    <StackPanel>
		<TextBox Text="{Binding TaskDescription, Mode=TwoWay}" />
		<Button Command="{Binding StoreItemCommand}">Store item</Button>
    </StackPanel>
</Page>

The most important thing for a View to know is which Viewmodel it needs to talk to! This is specified through setting the DataContext attribute: We simply assign a new instance of the CreateViewmodel to the CreatePage’s DataContext attribute either in XAML or C# code. With this, we’re able to reference Viewmodel properties and commands!

The rest of the XAML file just contains one TextBox to display (and edit) the new to-do-item’s task description, and a button to store the item. In real-life applications, of course you’re free to style the page design as you like by using every fancy XAML feature you know, but for this example I’ve kept it simple.

Both the TaskDescription property and the StoreItemCommand exist not in the View class itself, but in the Viewmodel we’ve referenced as DataContext, therefore we cannot access them directly but must use the {Binding ...} syntax. This way, the TextBox’ Text attribute will at runtime be filled with the current content of the Viewmodel’s TaskDescription property, and (since the Viewmodel raises the PropertyChanged event) the TextBox will be updated whenever the property’s content changes. By adding Mode=TwoWay to the binding expression, we ensure that the TextBox’s content will also be written back to the Viewmodel property when the user types in some text (note that this addition is not necessary in WPF as the WPF TextBox enables two-way binding by default, as I’ve pointed out in this separate blog post).

Similarly, the button’s default user event (the click or tap event) is redirected to the Viewmodel’s StoreItemCommand. This means, every time the user taps or clicks on the button, the command’s Execute() method is called, which again invokes the Viewmodel’s internal StoreItem() method!

The ListPage example

<Page x:Class="App1.Views.ListPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewmodels="using:App1.Viewmodels">
	
	<Page.DataContext>
		<viewmodels:ListViewmodel />
	</Page.DataContext>

    <ListView ItemsSource="{Binding Items}">
		<ListView.ItemTemplate>
			<DataTemplate>
				<TextBlock Text="{Binding TaskDescription}" />
			</DataTemplate>
		</ListView.ItemTemplate>
	</ListView>
</Page>

This page looks very similar to the first one, as it also binds itself to a Viewmodel using the DataContext attribute, and uses the {Binding ...} syntax to access Viewmodel properties.

The obvious difference is that Items is not a simple string property, but a collection of type ObservableCollection<ToDoItemModel>, which means that is contains complex objects itself. By binding it to the ListView’s ItemsSource attribute, we instruct the ListView to repeat certain XAML assignments for each item present within the collection. The actual assignments that shall be executed for each item are defined within the ListView’s ItemTemplate attribute: In this example, we just want to display a TextBlock containing the task description for each to-do item.

Outside the ListView we could not have directly accessed the TaskDescription property, since it does not exist within the Viewmodel, but rather in one member of the Items collection. This is only possible within the DataTemplate element, because here the context changes to the members of one ListView item, which means that – since each ListView item is of type ToDoItemModel – we can access all the public members of the ToDoItemModel class!

Now it’s time to dig a little deeper into the .NET MVVM implementation: Continue with part #5 (Intercepting Data Bindings)!

Permanent link to this article: http://www.mobilemotion.eu/?p=1306&lang=en

Oct 30

The very basics of MVVM #3: Getting ready for the show

After having discussed the basic structure of MVVM in part #1 (what’s it all about) and the contents of the Model layer in part #2 (I do it with models), this article covers the Viewmodel layer.

In nearly all cases, there exists exactly one Viewmodel for each View that is present within an application. A View can generally be explained as a visual screen presented to the user (e.g., a window in WPF, a page on Windows Phone, and so on) – but we’ll discuss that in detail in the next article. A Viewmodel has two basic purposes:

  1. To collect and aggregate data that shall be presented in the View and make it accessible for the View, and
  2. to execute the application logic on user interactions with the View.

Providing data for the View

This part is easy to implement, as it generally follows the structure we’ve already learned from the Model layer. Therefore, each Viewmodel should implement the INotifyPropertyChanged interface. It contains public properties – each one representing one data item or one group of data items to be displayed in the View – each of which should raise the PropertyChanged event in its setter.

The data types of most of these properties will probably be the Models created in the previous step, but also simple “primitive” data types such as string, int, bool, etc. might be used for simpler data items.

In addition, a common task at this layer is to create collections of data items and provide them as public properties to be presented in some kind of list box in the View. This is generally straightforward: Also these properties need to raise the PropertyChanged event in their setters. However, there’s one more thing to keep in mind: Changing such a collection’s content does not always result in the property’s setter being executed – for example, you can add items to, or remove items from a collection, or change the content of one of the collection’s items through indexing, and all those operations will not re-create the collection from stack, so the RaisePropertyChanged() method in the setter is never reached and the View will not be notified about the changed! Fortunately, the .NET framework provides a solution for this problem: Simple use the ObservableCollection as collection type, as this type will raise the PropertyChanged event even on simple manipulation operations. An example of how to use this type in practice is presented later in this article.

Invoking application logic on user interations

In this regard, we need to distinguish between presentation logic (e.g., sorting or filtering an existing collection of data items) and business logic (e.g., communication with web servers, databases, the file system, device sensors, etc.): The former is done in a separate method directly within the Viewmodel, while the latter does not actually fall within the MVVM pattern and will typically include some helper classes that do all the stuff with the Viewmodel only calling those helper classes and methods.

In both cases, there will be a (private!) method within the Viewmodel that either executes the presentation logic or calls an external helper class. The interesting part is to provide an interface that allows the View to access and invoke those private methods on user interactions. In practice, this is done through Commands. A command is a public property (and therefore accessible for the View) that provides a public Execute() method – this method is typically invoked by the View, and it should therefore execute the predefined private helper method.

Note that the .NET framework only contains an interface called ICommand but we need to implement the actual command on our own. The examples presented later in this article contain such a command called DelegateCommand – there will be a separate article (part #6) to discuss how such a command implementation typically looks like and how it can be used!

Example #1

Our example to-do list application will contain two Views: One to create a new to-do item, and one that lists all existing items. Therefore, we need two Viewmodels: let’s call them CreateViewmodel and ListViewmodel. The following code snippet shows the CreateViewmodel, this one simply contains a string property representing the new item’s task description (its is-done flag will be set to false automatically, since it’s a totally new item), and a Command that invokes a method which actually stores the new to-do item.

public sealed class CreateViewmodel : INotifyPropertyChanged
{
	private string _taskDescription;
	public string TaskDescription
	{
		get { return _taskDescription; }
		set
		{
			if (!_taskDescription.Equals(value))
			{
				_taskDescription = value;
				RaisePropertyChanged("TaskDescription");
			}
		}
	}

	public DelegateCommand StoreItemCommand { get; set; }

	public CreateViewmodel()
	{
		StoreItemCommand = new DelegateCommand(StoreItem);
	}

	private void StoreItem()
	{
		var item = new ToDoItemModel
		{
			TaskDescription = this.TaskDescription,
			IsDone = false,
		};
		//TODO: actually store this object in some database...
	}
}

In this example (and the next one), I omitted the implementation of the PropertyChanged event and its RaisePropertyChanged() method, since they look exactly the same as in the Model example shown in the previous blog post. I also omitted the implementation of the DelegateCommand type, as it will be explained in detail in part #6 of this series of articles.

Note that the Command is specified through three parts:

  1. The Command itself is a public property (which can be implemented as auto-property as it doesn’t need to raise the PropertyChanged event since its content will never change)
  2. The method to be executed on user interactions (e.g., when the user clicks a Store item button) is declared private
  3. The Command is initialized in the Viewmodel’s constructor with this private method passed as parameter

Now, when the user actually clicks that button, the View calls the Command’s Execute() method, which invokes the desired method within the Viewmodel!

Example #2

The ListViewmodel is even simpler:

using System.Collections.ObjectModel;

public class ListViewmodel : INotifyPropertyChanged
{
	private ObservableCollection<ToDoItemModel> _items;
	public ObservableCollection<ToDoItemModel> Items
	{
		get { return _items; }
		set
		{
			_items = value;
			RaisePropertyChanged("Items");
		}
	}

	public ListViewmodel()
	{
		LoadItems();
	}

	private void LoadItems()
	{
		IEnumerable<ToDoItemModel> databaseItems = //TODO: load items from database
		var sortedItems = databaseItems.OrderBy(x => x.IsDone);
		Items = new ObservableCollection<ToDoItemModel>(sortedItems);
	}
}

This one contains one property of type ObservableCollection that holds all our ToDoItemModel objects. In addition, there is one method for fetching the data from the database. Any database access helper function will return the list of data items as a simple IEnumerable, so we need to convert it to an ObservableCollection, as explained above. In addition, I decided to sort the items in order to have all done items grouped together. In contrast to the Store() method in the CreateViewmodel, the LoadItems() method is not invoked by the user through a command, but only once during startup (called from the Viewmodel’s constructor).

The next blog posts will show how to use these two Viewmodels to actually create a visual user interface: The very basics of MVVM #4: Enjoy the View

Permanent link to this article: http://www.mobilemotion.eu/?p=1298&lang=en

Oct 25

The very basics of MVVM #2: I do it with models

As promised, I’ll present each of the three layers of the MVVM architecture in detail – let’s start with the data Models! Please note that this series of blog posts started with a general overview of the MVVM pattern: The very basics of MVVM #1: What’s it all about. If you haven’t already, consider reading this introduction first!

Since the Model layer is the lowest layer in the MVVM hierarchy, and it does not need any knowledge about the other two layers, this is going to be a rather short article. Therefore I’d like to to start with something a bit off-topic, but nevertheless important to know:

Project structure

As I pointed out already, there are very few strict rules to follow in the MVVM world. There is, however, a set of best-practice guidelines which might be a good idea to follow, especially in the beginning, since they make life easier (as I will point out shortly). One of these concerns project structure: Typically, your project will contain three folders representing the three layers: Models, Views, and Viewmodels. (The last one is also often called ViewModels to resemble the fourth letter in the MVVM abbreviation, but that’s a personal preference.) Each code file is placed within one of these folders, depending on which layer it belongs to, and its namespace is chosen to resemble the parent folder. In large projects, it might be useful to create sub-folders and branched namespaces within these to distinguish between project parts.

This reduces the necessary effort for someone to understand your code, and of course it also allows you to quickly familiarize with other developers’ code and take over foreign projects, for example. But in addition, this separation of code files is a crucial requirement for multi-platform development: If you ever decide to publish the application for another platform, it is necessary to place the Model, Viewmodel and View classes in separate assemblies – easily done when already located within different folders and namespaces, potential cause of headache if not!

Of course, the project setup is not limited to these three folders. Since you’re using MVVM for building UI-centered applications, there might be images, video or audio files etc. to be used in the user interface, so you’ll want put them within an image or assets folder. In addition, there are code files that belong to one of the MVVM layers, but are usually places outside of the three folders – one example is the Converters folder that is typically found in nearly every MVVM project, although it contains ValueConverters that would belong to MVVM’s View layer. Finally, since MVVM regards only the UI-centered parts of the application, there might be other folders containing all other code files that do not fit into the MVVM pattern.

Finally: The data model

Alright, you’ve waited long enough, here we go: The idea behind the Model layer is to encapsulate all data items that will be used (and somehow presented to, or manipulated by the user).

The first step would be to make a list of data entities that will be used – for example, in a to-do list application, you might need an to-do-item entity, that contains attibutes such as task, done, etc. Speaking in terms of coding, ToDoItem will be a Model class, containing Task and IsDone properties. The Model is only responsible for data structure – for example, a to-do items’s task description will probably be stored in a string property. It does not care about how the text stored within this property is formatted to be displayed on the screen, and it is not responsible for fetching the textual information from a database (or from wherever it comes).

As mentioned earlier, since MVVM is only a design pattern, it consists of suggestions covering code structure rather than strict rules which APIs and frameworks to use, so it can theoretically be used with any programming language. On the other hand, especially .NET WPF, WinRT, Silverlight and the various XAML dialects have been developed with MVVM in mind, which means that there are best-practive approaches on how to implement the MVVM pattern in practice. In C#, a sample implementation of the above-mentioned ToDoItem Model class could look as follows:

using System.ComponentModel;

public class ToDoItemModel : INotifyPropertyChanged
{
	private string _taskDescription;

	public string TaskDescription
	{
		get { return _taskDescription; }
		set
		{
			if (!_taskDescription.Equals(value))
			{
				_taskDescription = value;
				RaisePropertyChanged("TaskDescription");
			}
		}
	}

	private bool _isDone;
	public bool IsDone
	{
		get { return _isDone; }
		set
		{
			if (_isDone != value)
			{
				_isDone = value;
				RaisePropertyChanged("IsDone");
			}
		}
	}

	public event PropertyChangedEventHandler PropertyChanged;

	protected virtual void RaisePropertyChanged(string propertyName = null)
	{
		PropertyChangedEventHandler handler = PropertyChanged;
		if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
	}
}

This looks like a simple data-container class, the only two remarkable things are

  • the fact that the Model class inherits from the INotifyPropertyChanged interface,
  • and the PropertyChanged event that is raised by each property’s setter.

The PropertyChanged event indicates that one of the data attributes contained within the Model class has changed (therefore it is raised from within each attribute’s setter) – each class con subscribe to this event to be informed whenever the Model’s content has changed. In practice, especially classes belonging to the View layer (windows, pages, etc.) will be interested in this notification event: Remember that the Model class contains data items to be presented to the user by a View, so the View must know when to re-draw itself to reflect the changed data items.

(The reason why this notification process is realized through an event is the hierarchical structure of the MVVM layers. Remember that, according to MVVM rules, Models may have no knowledge about Viewmodel and View layers, so it’s not possible to directly access any View class and inform it about a change in the data content.

And – by the way – the PropertyChanged event is also the reason why we (unfortunately) can not use auto-properties for public properties of data Models, because otherwise we’d not be able to intercept the property’s setter and raise the event…)

Don’t be confused by this event-based callback mechanism. In practice, all you need to remember that Model and Viewmodel classes should always implement the INotifyPropertyChanged interface, and that each property setter should raise the PropertyChanged event after actually updating the property’s content.

One final thing that should be noted is that all properties that will be used by the View to present data need actually to be public, even if the Model class is defined within the same assembly as the View (and you’d think that marking them as internal should be sufficient), as I pointed out in a separate blog post!

That’s it so far, read on in part #3 about how to make use of this simple data Model!

Permanent link to this article: http://www.mobilemotion.eu/?p=997&lang=en

Oct 22

The very basics of MVVM #1: What’s it all about

When I gave a talk about how to utilize MVVM and Portable Class Libraries for multi-platform development a few months ago at one of the Viennese Windows Phone Developer Community After-Work events, I received more questions about MVVM principles and basics than about Portable Class Libraries and the cross-platform thing. Therefore I finally decided to spread the word and create a series of blog posts summarizing “the very basics” about the Model-View-Viewmodel pattern and showing best-practice code examples to use the pattern in real-life applications.

A warning to all the professionals out there: This series is to be understood as introduction into the topic and will contain (as the title says) basic stuff – so if you know the MVVM pattern very well and use it regularly in practice, the following articles will be rather boring for you. But there might still be more advanced articles covering the MVVM topic following in the future, so make sure that you check this category regularly (or bookmark blog.mobilemotion.eu/mvvm)!

What’s it all about?

As the name suggests, the Model View ViewModel (MVVM) pattern is not a strict framework but a design pattern. This means that there are no rules that instruct how to write code or which libraries or methods to use, but rather suggestions about how to structure the codebase. It should be noted that the MVVM pattern only describes the structure of those code parts that are necessary for presenting some kind of user interface – if a project does not include any visible UI, there is no point in trying to follow the structure suggested by the MVVM pattern.

On the other hand, there is always something beyong MVVM: No real-life application will only contain data and a beautiful UI to display this data – every App needs to communicate with some backend on a web server, with a database, with the file system, with device sensors, and so on. The MVVM pattern only describes the structure of those code parts that are responsible for arranging and displaying data via a graphical user interface, this doesn’t mean that an application may not consist of additional code files that do not fit in the structure discussed in this and the following articles!

This means it’s all about …

… architecture!

MVVM suggests that you divide your codebase into three layers, each of which has a clearly defined purpose: The Model, View, and Viewmodel layers. These are responsible for data structure, presentation logic, and UI presentation, respectively. Each component within your codebase will belong to one of these three layers – and therefore should only include logic necessary to reach the respective layer’s purpose.

We’ll have a detailed look at each layer in the following blog posts, but I think it’s important to give a quick overview of what each of the three layers does and how they are linked with each other:

  • The Model layer is solely responsible for providing the necessary data structure for all the data items that will somehow be presented within the user interface.
    It does not specify where the data comes from (e.g., a database, files, user input, the Internet, …), but only how the data is structured – meaning which data items are about to be used within the application, and as which basic data types they can be described within your programming language.
  • The View layer contains the actual user interface: Windows in case of a desktop application, web pages in case of a web project, etc.
    This includes all user controls that shall be present within a window, a page, etc., and all commands that can be triggered by the user (in order to invoke business logic functions, which themselves however are not part of this layer).
  • Finally, the Viewmodel layer acts as link between those two:
    It fills the data items defined on the Model layer with actual data, arranges this data in order to be presented to the user, and provides it for the View layer to display it. However, it does not actively fill the visible user interface items with the data, this is in the View layer’s responsibility!
    In addition, the Viewmodel layer takes over all user actions that are triggered within the View layer and calls the actual functions to be carried out.

The most important thing (and the fact that distinguishes MVVM from traditional UI-centric coding) is that these three layers are structured hierarchically, as illustrated in the following scheme:

MVVM pattern: Hierarchy of layers

 
 
 
 
 
 
 
 
 
 
 
All components located on the Model layer (typically called Models) don’t know anything about the Viewmodel and View layers: They don’t know how they will be arranged for presentation, and how they will be displayed. They don’t even know which components exist on the Viewmodel layer.

Instead, all components on the Viewmodel layer (called Viewmodels) know about the existence of the different Models, and may reference them in order to arrange them for presentation and display.

Similary, the Viewmodels don’t know anything about the View layer – they just provide data to be displayed in the Viewmodel, and they offer functions that can be triggered by the user, but they don’t know which window, web page, etc. will display this data in which way.

Instead, the windows, pages, etc. on the View model (globally referred to as Views) reference the Viewmodels, retrieve data items contained within those Viewmodels and call business functions defined within Viewmodels.

Why should I stick to such a strict pattern?

Let’s take a look at some of the advantages of following the MVVM pattern in real-world projects:

  • The separation of concerns between the three layers, the well-defined interfaces between the layers, and the hierarchical dependencies (Views depend on Viewmodel and Viewmodels on Models, but not vice versa): All this ensures that components belonging to different layers can be worked on individually and simultaneously. For example, UI designers can design the Views while at the same time programmers are coding the Viewmodels.

Ok, this is convenient for large companies working with several teams simultaneously. What about single developers?

  • It’s really easy to inherit code from other developers – if another programmer started to work on a project and passes it on to you, you’ll get used to the code structure very quickly, because you already know on which layers certain code parts are to be expected.

Have you ever tried to create automatic test cases of UI functions? MVVM also helps in this regard:

  • Since all business functions reside at the Viewmodel layer, they can be accessed without actually creating and using the graphical UI. This means Viewmodel methods can easily be tested using unit tests.

Still not convinced? Try the last one:

  • It enables real multi-platform development. Let’s assume you’ve got a totally innovative idea for an application, and would like to publish it as desktop, tablet, smartphone, and web app – all you need is create different views for each platform, but both Models and Viewmodels (and with that, all of your business logic) can be used on all platforms without changing one line of code!

In reality, of course there are enough obstacles on the way – but on the other hand, there exist a lot of frameworks, libraries and best-practive approaches to help you on the way!

Let’s get started!

The next blog posts will cover each MVVM layer in detail, including code samples. Start with The very basics of MVVM #2: I do it with models

Permanent link to this article: http://www.mobilemotion.eu/?p=927&lang=en

Oct 15

Custom cookies in WebView request

I was recently working on a Windows Store project that included presenting some web page to the user, with the additional requirement to automatically fill in the login page. Technically, this included setting some cookies before sending the HTTP request.

Displaying a web site within a Windows Store app always includes a WebView control – however, when simply calling its Navigate method to actually load the page there is no way to influence the actual HTTP request, set specific headers etc.

On the other hand, WinRT provides the System.Net.Http.HttpClient class for dealing with HTTP requests in code, meaning without visualizing the response page. Using HttpClient, it’s easy to customize the HTTP request by adding custom cookies to the HTTP handler’s CookieContainer:

var pageUri = new Uri(TargetPage);
var handler = new HttpClientHandler();
handler.CookieContainer.Add(pageUri, new Cookie("key", "value"));
var client = new HttpClient(handler);
var response = await client.GetAsync(pageUri);

By awaiting the HTTP response and reading its content as string, it would be possible to display the page’s content within a WebView:

response.EnsureSuccessStatusCode();
string html = await response.Content.ReadAsStringAsync();
webView.NavigateToString(html);

The problem is: The page is displayed as if it was the actual web page, but it really is a local copy of the page’s content – as soon as the user clicks any hyperlink to navigate to another page, the authentication cookie is lost because it is set on the HttpClient, not on the WebView.

So, is there a way to combine those two approaches? The Windows 8.1 WebView control includes the NavigateWithHttpRequestMessage method, which (finally) allows exactly this behaviour: Instead of simply passing a URI to be shown by the WebView (as with the traditional Navigate method), it allows to create a custom HTTP request and tell the WebView to visualize this request’s response.

The HttpRequestMessage to be passed to this method contains the HTTP method (GET or POST) and the target URI. Don’t try to add cookies directly by manipulating the HttpRequestMessage.Headers.Cookie collection, as these will be overwritten as soon as the request is sent – you’ll need a different approach here: Add a custom HTTP filter, and and all the desired cookies to this filter’s CookieManager:

var pageUri = new Uri(TargetPage);

var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
var cookie = new Windows.Web.Http.HttpCookie("key", pageUri.Host, pageUri.LocalPath);
cookie.Value = "value";
filter.CookieManager.SetCookie(cookie, false);

var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, loginUri);
webView.NavigateWithHttpRequestMessage(request);

The interesting part here is that there seems to be no correlation between the filter and the request message. In fact, both operate on a shared CookieContainer that is valid for the whole App. This means when adding cookies to the filter’s CookieManager, they are actually stored in a global container and are therefore valid for each request that is sent from any WebView control within the App.

Permanent link to this article: http://www.mobilemotion.eu/?p=1294&lang=en

Older posts «