Windows 8 calendar control

As far as I see, lot of people search how to add the calendar or datepicker control to their windows 8 applications. Though there is a control which is called WinJS.UI.DatePicker, it is actually not a date picker, it is just 3 comboboxes in one row. But because of the fact that Windows Store apps can be written by using HTML, CSS and Javascript, you can use any HTML controls which was designed for web sites in the internet. Here is a link to a short review of 21 free HTML datepickers.

In this post I will show how to use the most popular JQuery UI Datepicker. You should build your Windows Store app by using Javascript, because for obvious reasons it won’t work with XAML and C# (though you can try to use this control for C# apps, but I’m not sure that it will work).
Here is the screenshot of the app running on the simulator:


At first, it is necessary to download 3 files. Though it is possible for internet web sites to refer to javascript libraries without downloading them, windows store applications can’t do this, they can use only offline javascript files.
1. jQuery 1.8.3 (the latest stable version at the moment of writing this post, but you can use any other version)
2. jQuery UI
3. jQuery UI style sheet

The first thing that you should do is to modify the jQuery 1.8.3 library. You should add 1 line at the beginning of the file and 1 line at the end:

MSApp.execUnsafeLocalFunction(function () {
// the original file

Like this:


Then add these 3 files to appropriate folders of the project:


Add links to these files to the head section and add an input element with javascript code to the body section. The whole file looks so:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <title>DatePicker Sample</title>

    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
    <script src="/js/jquery-1.8.3.js"></script>
    <script src="/js/jquery-ui.js"></script>
    <link href="/css/jquery-ui.css" rel="stylesheet" />

<!-- These links are not necessary in my application, but they can be useful in other applications -->
<!--<link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>-->
    <h1>DatePicker Sample</h1>
    <p>Date: <input type="text" id="datepicker" /></p>

    <script type="text/javascript">

The source code of the sample application:


Silverlight and WPF Timeline Scroll View

Here is another control which I had for a long time but only recently have decided to arrange the source code and post it here.
That’s how it looks:

Although it looks very complex, actually it is quite simple: it is just the styled ScrollBar control on the left and the ScrollViewer on the right.

The grey control with years on the left is the UserControl called TimelineScrollBar, mark-up of which looks so:

	<ItemsControl x:Name="rowItems">
				<Grid Height="{Binding Height}">
					<TextBlock Text="{Binding Text}"/>


	<ScrollBar x:Name="VerticalScrollBar" Style="{StaticResource TimeLineScrollBarStyle}" />

The rowItems items control and the VerticalScrollBar scroll bar are related to the dependency properties TimeItemsSource and BoundScrollviewer which should be set outside and are handled in the code-behind:

<Views:TimelineScrollBar x:Name="timelineScroller" 
 TimeItemsSource="{Binding TimelineItems}" 
 BoundScrollViewer="{Binding ElementName=listScroller}" 
 Width="120" />

The TimelineItems is the special collection of items { Text, Height}. These properties must be present and they are quite generic, so you can use any labels instead of years.

The generation of these items is the most difficult part, after that everything is quite easy.

Create the view model:

public class MainViewModel
	public List<TestItemViewModel> Items { get; private set; }

	public List<TimelineItemViewModel> TimelineItems { get; private set; }

Set is as DataContext to the view:

	<Views:TimelineScrollBar x:Name="timelineScroller" 
 TimeItemsSource="{Binding TimelineItems}" 
 BoundScrollViewer="{Binding ElementName=listScroller}" 
 Width="120" />

	<ScrollViewer x:Name="listScroller">
		<ItemsControl x:Name="list" ItemsSource="{Binding Items}" ItemTemplate="{StaticResource itemTemplate}" ItemsPanel="{StaticResource itemsControlTemplate}" />

In this example I used the ItemsControl class for simplicity. If you want to use it with the ListBox class, you should change its ControlTemplate and retrieve the name of the inner ScrollViewer control so it can be bound to the timeline scroll bar.

The source code of my example you can download here:

WPF Scheduler

Several years ago I found a Silverlight sample application on one of the sites of Microsoft, that application was called something like Patient Journey Demonstrator and didn’t serve any real purpose but to show what can be created by using Silverlight.
I remember that I decompiled the source code and tried to build something similar, but eventually I didn’t used those controls in any of my applications. Anyway, here is one of the interesting controls:

This controls looks good by the way: you can expand and collapse items representing hours, you can drag and drop appointments from one time to another, also there are some unavailable gray cells which it is not allowed to drag items to. The only one inconvenience is that all items should take the same amount of time and can’t cross the border of an hour.

This code is 2 years old and isn’t implemented well, but at least it works. Maybe some day I’ll rewrite it and make it more useful, as soon as I have a time.
Source code:

WPF Drag and Drop implementation

Some time ago I searched how to implement the drag and drop functionality in my WPF application. But all examples that I found either contained much of unmaintenable code or worked only for a specific task and it was difficult to add that code into my existing application.

But recently in the Microsoft training course book (10262A Developing Windows Applications) I’ve found quite good example how to implement this functionality by using expression blend behaviors. By the way, the actual implementation were taken from this post.

Now it is very easy to use the drag and drop out of the box, just add the following 3 lines to a source element:

    <dd:DragDropBehavior IsDragSource="True"/>

And the following 3 lines to a target element:

    <dd:DragDropBehavior IsDropTarget="True" Dropped="DragDropBehavior_Dropped"/>

The i prefix is defined as xmlns:i=”clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity”, you can use this library after you install Expression Blend SDK or you can find it in the archive attached to this post.

Which element is the source and which one is the target – you should determine it logically. For example, if you want to move items from one ListBox to another one, the drag source will be the item template of the first ListBox (because it is the item which is dragged), the drop target will be the second ListBox itself (although it is still possible to set the drop target to the item template, it doesn’t work well for the empty listbox).
The code will look something like this:

<ListBox ItemsSource="{Binding Items1}">
            <TextBlock Background="Transparent">
                    <dd:DragDropBehavior IsDragSource="True"/>
                <Run Text="{Binding Title}" /><Run Text=": "/><Run Text="{Binding Value}" />
<ListBox ItemsSource="{Binding Items2}" Grid.Column="1" DisplayMemberPath="Title">
        <dd:DragDropBehavior IsDropTarget="True" Dropped="DragDropBehavior_Dropped"/>

And here is how it looks after you run the application:
wpf drag and drop sample

The source code of the behavior and sample application you can download here:
If you want some extra features – you can freely write your suggestions in comments, I’ll think what I can do.

The necessity of a ViewModel class for each Model class

It is well known that you need a ViewModel if you want to add property change notification or validation to a Model. But what if the Model and ViewModel classes don’t differ at all? Should you create a ViewModel class if it has the same set of properties that the Model class has? The answer is yes, absolutely. The brief reasons are separation of layers and loose coupling. But I know that these abstract terms don’t sound very convincing so I’ll describe my point of view more particularly in this post.

As an example I’ll use this data source class (which can be either a web service, or a database, or a file, whatever) and this model:

public interface IModelSource
    SettingsModel GetSettings();

public class SettingsModel
    public string DefaultPage { get; set; }

    public string DownloadsFolder { get; set; }

    public bool AutoStart { get; set; }

So we should choose which approach to use.
Just to bind the model as it is:

SettingsModel model = source.GetSettings();
this.DataContext = model;

Or to use the extra ViewModel layer and convert the model before binding:

SettingsModel model = source.GetSettings();
SettingsViewModel viewModel = ConvertModelToViewModel(model);
this.DataContext = viewModel;

Let’s examine some cases and look at the differences between the approaches above.


1. Remove a property from the model class.
It happens quite often during development, this type of changes can be performed on the service side or in the database. So if to remove the AutoStart property, what will happens then?

The model-only approach
You will not be aware of the error and will not notice it until you run your application, navigate to the corresponding view and look at the Output window. There among messy messages you will see the notification about the binding error:
Runtime binding error
Also you should run your application in the Debug mode. If you start it by using the Ctrl+F5 combination, you will never find the error.

The viewmodel approach
You will be notified about the error almost immediately before you run the application. And you know: the earlier the bug is found – the easier to fix it.


2. Add a property of a complicated data type to the model class.
For example, this property of the Enum type:

NumberFormatCulture NumberFormat { get; set; }

The model-only approach
It isn’t clear how to bind this enum to the ComboBox control (I think, you will not display such programming language related values as “EnglishUS” to end users, won’t you?), so you’ll search it on Google or StackOverflow and eventually you’ll choose either a hacky solution (which will work only for the particular case) or you’ll agree to use the ViewModel (and admit wasting the time).

The viewmodel approach
Just add a few lines to the mapping configuration which can be easily bound to the ComboBox:

//Mapper.CreateMap ... 
.ForMember(vm => vm.NumberFormats, option => option.UseValue(
.ForMember(vm => vm.SelectedNumberFormat, option => option.MapFrom(
    m => TranslateEnum(m.NumberFormat)))


3. Change the structure of the model class.
For example, if to change some property of the string type to the property of another model type:

public PageModel DefaultPage { get; set; }

public class PageModel
    public string Url { get; set; }

The model-only approach
Again, you will not notice the error until you run the application and look at the Ouput Window (see p.1). Then you should run over all the xaml-markup in the view and correct bindings. And of course launch the application once again to assure that everything is fine after the changes.

The viewmodel approach
Just fix one line of the code in the mapping configuration:

//Mapper.CreateMap ... 
.ForMember(vm => vm.DefaultPage, option => option.MapFrom(m => m.DefaultPage.Url))

I must say that in this case the mapper doesn’t perform compile-time checking, but you can configure it so that it throws an exception if you try to map from the object type to the string type. And exceptions are any easier to notice and understand than debug messages in the Output window.


4. Project structure and maintenability
It isn’t a big advantage of the viewmodel approach in comparison with the above described points, but anyway, it is much better to have a good project structure when each view has a corresponding view model with the same class name prefix. You will not search which model class is bound to, for example, the SettingsView class (which model class: UserSettingsModel, ServiceSettingsModel? I don’t remember so I’ll take some time to find it out). You’ll just open the folder with view models and immediately see the corresponding SettingsViewModel class.


The most popular exuse not to create the extra layer is because it allegedly takes much time. But if to calculate the exact amount, the statement will be far from the truth.
– Add the AutoMapper library by using the NuGet package manager – 20 second (this task is performed only once)
– Create a new ViewModel class and just copypaste all of the properties of the model – 30 seconds
– Configure the mapping by using code-snippets – 5 seconds per property.

So it’ll take something about 1-2 minutes to create a ViewModel and I can’t say that it is a “huge amount of time”. And this amount is nothing in comparison with the time wasted on the above described points if to use the wrong approach. Don’t afraid to spend few minutes now, it will save many hours in the future.

WPF and Silverlight design patterns

In this post I’ll describe the design patterns which are used in large and complex applications in order to simplify their development and maintenance.

Model View ViewModel
Separates Model and View by introducing the intermediate layer which is called ViewModel. It is a some kind of a “super converter” which adds additional properties and behavior to the model. Also commonly used as a replacement of code-behind.
The most common features of ViewModel:

  • Property changes notification with the INotifyPropertyChanged interface
  • Validation with the IDataErrorInfo or INotifyDateErrorInfo interfaces
  • Event handling of View events
  • Invocation of WCF services
  • Converting of model properties from one data type to another

Example of Model and ViewModel:

public class UserModel
	public string Name { get; set; }

public class UserViewModel : IDataErrorInfo, INotifyPropertyChanged
	private string name;

	public string Name
		get { return name; }
			name = value;

	public ICommand ChangeNameCommand { get; set; }

	public string Error
		get { throw new NotImplementedException(); }

	public string this[string columnName]
		get { return this._validator.GetErrors(columnName).FirstOrDefault(); }

	public event PropertyChangedEventHandler PropertyChanged;

	private void RaisePropertyChanged(string propertyName)
		if (this.PropertyChanged != null)
			this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

Wikipedia. Model View ViewModel
Developer’s Guide to Microsoft Prism. Implementing the MVVM Pattern
Never In Doubt: MVVM Backlash


Dependency Injection
The purpose of this pattern is to get rid of using of external classes and to use interfaces instead.
This pattern adds the following benefits:

  • Allows to write unit tests because interfaces can be replaced by “fake” classes
  • Allows to change one interface implementation by another without affecting or changing existing objects

For example, this class:

public class MyViewModel
	public MyViewModel()
		this.SomeProperty = Resources.String1; // the static class call

	public void Refresh()
		var model = new MyWcfServiceClient().GetModelById(this.Id); // the service creation

        // initialize the corresponding properties of the view model

should be rewritten so:

public class MyViewModel
	public MyViewModel(IResourceManager resourceManager, IServiceClient serviceClient)
		this._resourceManager = resourceManager;
		this._serviceClient =  serviceClient;

		this.SomeProperty = this._resourceManager.String1;

	public void Refresh()
		var model = this._serviceClient.GetModelById(this.Id);

        // initialize the corresponding properties of the view model

Wikipedia. Dependency injection
MSDN Magazine. Design Patterns: Dependency Injection


Modular Application
This concept is based on the logical division of application components and if you use several projects with different functionality, you already use a some kind of modules. For example, if your solution has projects like Application.Mail, Application.Calendar, Application.Tasks – it has 3 modules as well.

Besides the above mentioned logical division, the Prism framework adds the following features:

  • Allows to add modules after the application is released (some kind of plug-ins)
  • Allows to defer module loading and load some of them on demand

Developer’s Guide to Microsoft Prism. Modular Application Development


Event Aggregator
This pattern is known as Messenger in the MVVM Light Toolkit. Implements the “publish-subscribe” model. For example, if one view model should call a method of another view model, it can be done by using two ways:
1. Bad practice: The first view model gets the second view model as the constructor parameter and then calls the necessary methods directly by using the code like this._otherModel.OnUserUpdated(this).
2. The preferred approach: The second view model publishes an event, the first one subscribes to it and handles appropriately.

Martin Fowler. Event Aggregator
Developer’s Guide to Microsoft Prism. Communicating Between Loosely Coupled Components


Allows to get rid of the code-behind and handle button clicks inside a view model. Also it is useful when the same action is invoked from the application menu, context menu, toolbar and buttons, so you don’t need to write separate event handlers and you can use just a single command everywhere.
Besides the method invocation, commands in WPF affects the IsEnabled property of buttons and menu items as well: if a command can’t be executed, all the invoke buttons will be disabled.

Wikipedia. Command pattern
MSDN. Commanding QuickStart

Windows 8 Items controls

In addition to the single-item controls, Windows 8 as well as WPF provides controls for multiple child items by using classes derived from the ItemsControl class.

Common items controls in Windows 8 are:
ListBox – A list of selectable items (the same as the WPF counterpart).
ComboBox – A selection control that combines a non-editable text box and a drop-down containing a list box (the same as the WPF counterpart).
FlipView – Displays one item at a time and allows to traverse its items by using either pop-up arrows or the “flip” gesture.
ListView – Displays a list of items, similar to the ListBox control, but with a difference that it can be used with the JumpViewer control (I’ll try to describe it some time later).
GridView – A specialized ListView which displays items in a form of grid. The same can be achieved by using the ListView control and the wrap panel inside its ItemsPanelTemplate.

Here are sample screenshots of above described controls:

Windows 8 ItemsControls: Listbox, ComboBox, FlipView, ListView

Windows 8 ItemsControl: GridView

The following items controls are not available in Windows 8:

I hope some of them will be available after the final release in the form of Toolkit, like it was with Silverlight.