Scheduled Notifications in Android using Alarm Manager


Few months ago, I wrote an article for DNC Magazine titled “Hello Xamarin.Forms!” which was later republished online on This article demoed all awesomeness of Xamarin.Forms with a simple Vehicle Service Reminder app as an example. One of the aspects of the app is to remind users when their vehicle was due for service. While I showed how to go about doing that in iOS and Windows Phone, I left the Android part as an action item for the readers. While some of you may have got it already, if you haven’t, here’s how you do it –

In Android, unlike in iOS, local notifications does not take the fireDate as a parameter while configuring Notifications. So we have to split this task into two –

  • Use system alarm services to wake your app up at a specified time (Using Alarm Manager)
  • Write the code to notify users in the “OnReceive()” method of the Broadcast Receiver

Using Alarm Manager

AlarmManager class is used to schedule your application to be run at some point in the future. Create an Alarm Intent, specify the broadcast receiver and finally set the time when you intend to wake your app up.

public void Remind (DateTime dateTime, string title, string message)

	Intent alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver));
	alarmIntent.PutExtra ("message", message);
	alarmIntent.PutExtra ("title", title);

	PendingIntent pendingIntent = PendingIntent.GetBroadcast(Forms.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
	AlarmManager alarmManager = (AlarmManager) Forms.Context.GetSystemService(Context.AlarmService);

	//TODO: For demo set after 5 seconds.
	alarmManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime () + 5 * 1000, pendingIntent);


Notifying Users

Now that the AlarmManager will ensure that your app is run at a specified time, you will have to write the code to notify users in the “OnReceive()” method of the Broadcast Receiver. In this case the broadcast receiver is the AlarmReceiver – a custom class subclassed from BroadcastRecevier.

public class AlarmReceiver : BroadcastReceiver
	public override void OnReceive (Context context, Intent intent)

		var message = intent.GetStringExtra ("message");
		var title = intent.GetStringExtra ("title");

		var notIntent = new Intent (context, typeof(MainActivity));
		var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
		var manager = NotificationManagerCompat.From (context);

					var style = new NotificationCompat.BigTextStyle();

					int resourceId;
					if (App.SelectedModel.VehicleType == "Car")
						resourceId = Resource.Drawable.Car;
					else if (App.SelectedModel.VehicleType == "Bike")
						resourceId = Resource.Drawable.Bike;
						resourceId = Resource.Drawable.Other;

					var wearableExtender = new NotificationCompat.WearableExtender()
			.SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId))

					//Generate a notification with just short text and small icon
		var builder = new NotificationCompat.Builder (context)
						.SetContentIntent (contentIntent)
						.SetSmallIcon (Resource.Drawable.ic_launcher)

					var notification = builder.Build();
					manager.Notify(0, notification);

The code above uses NotificationCompat.Builder and sets the WearableExtender which will ensure the notifications are also sent to the connected Android Wear device. To know more about wearable programming using Xamarin, don’t forget to check out the post on Tips for your First Wear App.

You can download the full source from my GitHub repo.

YouTube Android Player for Xamarin.Android

Xamarin-YouTube-Android-Player Have you tried embedding a YouTube video into your android app? May be you tried using the HTML to embed the YouTube player in a WebView. From a developer perspective they aren’t programmable – meaning if you wish to interact with the player like play, pause, forward, go full screen, change video quality etc from your app, there isn’t a straight way to do it. From a user perspective the experience isn’t nice and you definitely want to work a better way out. Fortunately, Google provides a slick native YouTube Player on Android platform and a player API written in Java. The player API is a set of client libraries that interacts with a service that is distributed as a part of the YouTube Android app itself. That said, you need to ensure that the YouTube App is installed in the user’s device beforehand. The advantage is – your app size does not bloat up and you can upgrade the client libraries to incorporate new changes to the YouTube app anytime. And, upgrading is not necessary if you do not care about new features or bug fixes.

Bringing this beauty to Xamarin in C#

Lot of developers out there haven’t unleashed the full potential of the Xamarin platform yet. One of the big wins for Xamarin over any other cross-platform solutions is the power to reuse the existing Java and Obj-C (in case of iOS) libraries in C#. Apps built-in Xamarin are fully native and anything that you can do with Java in Android or Objective-C/Swift in iOS can be done in C# using Xamarin. Java ecosystem is large and it is  likely that a functionality that you want in Xamarin.Android may have already been written in Java just like the YouTube Android player in this case. Technically, you will use Bindings to bring any reusable Java library to Xamarin.Android. Alternatively, you can use JNI framework or port the entire Java code to C# using an automated tools like Sharpen. In this case, I downloaded the YouTubePlayer API jar file  and bound this using the Java Bindings Library project which is part of my solution. This project generates C# dll of your jar file and they are referenced into my Android project just like any other C# dll.  I have plans of writing a dedicated post on bindings and you can expect that soon. For now, I suggest, you read the official documentation.

Using the YouTubeAndroid player in C#

The bindings project dll that is referenced into your main Android app has the full Java API in C# along with the beautiful features of C# that you can utilize – like anonymous methods, lambdas, Linq etc. The solution also includes a samples project that helps you understand each of the API features in detail. So, you can copy and paste the entire code “as is” to make it work with your app.

[Update:] See how @xakpc adds async-await feature to his YouTube Thumbnail sample and unleashes the full potential of C#.

Source Code

If all that you care is the binding library or you are aware of how to get started with it – Head straight to my github for download. Please note: You can execute theses samples only on a physical device that has YouTube App installed. If you have an emulator that has the Google Play Services installed then it may work there too – I haven’t tested this so can’t guarantee!

Before you start

Get a developer key from Google and register your application. Add your key to the DeveloperKey.cs file

public static class DeveloperKey
 public static string Key = "";

Simple PlayerView

This sample shows how to use a YouTubePlayerView to play a video.

Resource file (PlayerView.axml)

First add the player to your resource file –


In the onCreate() method, instantiate your YouTubePlayerView and initialize it with your DeveloperKey.

YouTubePlayerView youTubeView = FindViewById(Resource.Id.youtube_view);
youTubeView.Initialize(DeveloperKey.Key, this);

To start playing your video cue the video to the player’s playlist.

public override void OnInitializationSuccess (IYouTubePlayerProvider provider, IYouTubePlayer player, bool wasRestored)
if (!wasRestored) {
player.CueVideo("wKJ9KzGQq0w"); }

CueVideo method takes the YouTube video id that you want to play and loads them to your playlist. When user clicks play, well, they get played 🙂 Noticed the OnInitializationSuccess method that is overriden? I use a helper activity called YouTubeFailureRecoveryActivity as the base class for all the samples. This class handles all the failure and recovery mechanism in the Android player.

That’s it!

Don’t forget to take a look at the PlayerControlsActivity.cs file if you want to know how to interact with the player – like play, pause, seek to position, change player style etc.


Hope this helps you!


Say Hello to Nokia X in C# and Visual Studio


Nokia recently introduced the Nokia X family of smartphones, which provides users access to the world of Android. The good news for C# developers is that using Xamarin you can start writing apps for this platform from day 1. If you’re new to building Android apps in C#, do check out my blog post on “How I built an Android app in C# & Visual Studio in less than 24hrs” that I wrote few months back.


Setting things up

The core Nokia X platform is built on Android Open Source Project v4.1.2, which supports API level 16. That means you’ll be targeting API 16(4.1.2) for your app development. You’ll also need to install Nokia X specific packages in the Android SDK Manager.

Configure Nokia X specific packages

Start Android SDK Manager from Visual Studio.

  1. Select Tools > Manage Add-on Sites
  2. Open User Defined Sites tab and click the New… button
  3. Enter the following URL to the Add Add-on Site URL dialog:
  4. Click OK


Install Nokia X specific packages and API level 16

Be sure to install Nokia X System Image under Android 4.1.2(API 16)


You’ll also need to install the following extras:

  • Nokia X Device Definitions
  • Nokia X services
  • Nokia X USB Driver
  • Intel x86 Emulator Accelerator(HAXM) (optional)


Configure Nokia X emulator

Open Android Emulator Manager from Visual Studio and create a new emulator with the following configuration:

  • Give your emulator a name say Nokia-X
  • Select the Device Nokia X (480 x 800; hdpi)
  • Select Intel Atom (x86), if you have HAXM installed and Intel VT-X enabled (gives you a faster emulator)
  • Be sure to select Nokia X Services under Target
  • Have an SD card with a desired size
  • Select Use Host GPU as emulation options


Kick Start the Emulator

Nokia-X-Start Nokia-X_running

Hello World

Writing your first app on Nokia X using Xamarin is as simple as creating a regular Android app in Visual Studio.

File > New Project > Visual C# > Android > Android Application


In your project properties, be sure to compile your Android app with Version 16 or lower.


That’s it. Go Run your first app!


I had a simple code to Toast Notify with a custom message on a button click. When I ran it, I saw the message appearing on the top left corner instead of the usual Android toast. Looks like few things have changed here. Refer Nokia X Design Guidelines for changes that you must be aware of.

Nokia X Components

Nokia has shipped Xamarin components for their Nokia X SDK. Don’t forget to check them out at the component store.

Mike Bluestein has a nice post on Nokia HERE Maps component – Use Nokia X HERE Maps with Xamarin.Android.


– Cheers!

Adding custom buttons to iOS Keyboard in C# & Xamarin

What if you needed some extra keys for text input in your iOS app? Say for e.g.  if you needed text based emoticons on top of the standard keyboard for a chat application. Thankfully UIKit allows apps to have an accessory view above the system keyboard. The area above the keyboard is an extra UIView known as Input Accessory View which you can customize to add your extra keyboard buttons. To add an accessory view, all you gotta do is, set the InputAccessoryView property of the UITextView or UITextField  to an appropriate custom view.

Here’s how the extra keys on top of your standard keyboard looks like:


Following code sets the text based emoticons to the InputAccessoryView:

		public override void ViewDidLoad ()
			base.ViewDidLoad ();

			UIToolbar toolbar = new UIToolbar (new RectangleF(0.0f, 0.0f, this.View.Frame.Size.Width, 44.0f));

			toolbar.TintColor = UIColor.White;
			toolbar.BarStyle = UIBarStyle.Black;

			toolbar.Translucent = true;

			var myButton = new UIBarButtonItem (":-)",
				UIBarButtonItemStyle.Bordered, AddBarButtonText);

			toolbar.Items = new UIBarButtonItem[]{
				new UIBarButtonItem(":-)",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(":-(",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(";-)",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(":-P",
					UIBarButtonItemStyle.Plain, AddBarButtonText),
				new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
				new UIBarButtonItem(UIBarButtonSystemItem.Done, delegate {

			this.SampleText.KeyboardAppearance = UIKeyboardAppearance.Dark;
			this.SampleText.InputAccessoryView = toolbar;

		public void AddBarButtonText(object sender, EventArgs e)
			var barButtonItem = sender as UIBarButtonItem;
			if (barButtonItem != null)
				this.SampleText.Text += barButtonItem.Title;


In the above code, we create a UIToolBar with UIBarButtonItems of text based emoticons and set it to the InputAccesoryView property of the SampleText. AddBarButtonText method then handles the key input events.

Playing Input Clicks

You can play standard system keyboard clicks when a user taps in your keyboard accessory views. If you had gone through the apple documentation on Custom Views for Data Input referred earlier, then you would have noticed Objective-C code to do so. Here’s how we can do it elegantly in C#:

  • Create a custom class called MyUIToolBar that inherits from UIToolbar (since we’re using UIToolbar as the custom view for InputAccessoryView)
  • Override the property  EnableInputClicksWhenVisible and return true from it
	public class MyUIToolbar : UIToolbar
		public MyUIToolbar (RectangleF rect) : base(rect)


		public override bool EnableInputClicksWhenVisible {
			get {
				return true;

In the calling code, use the newly created MyUIToolbar

  MyUIToolbar toolbar = new MyUIToolbar (
new RectangleF(0.0f, 0.0f, this.View.Frame.Size.Width, 44.0f));

and make sure you play the sound when user clicks:

public void AddBarButtonText(object sender, EventArgs e)
  var barButtonItem = sender as UIBarButtonItem;
  if (barButtonItem != null) {
  this.SampleText.Text += barButtonItem.Title;
  UIDevice.CurrentDevice.PlayInputClick ();

Replace the entire keyboard (custom keyboard)?

At times you just want the textbox to input only the keys that you had set. It’s possible to replace the entire keyboard to a custom one. In this case, I just set our emoticon toolbar to InputView property instead of the InputAccessoryView . And this is what it outputs:


Source Code

You can download the complete source code from my github repo.

Happy C# Coding!!



How I built an Android app in C# & Visual Studio in less than 24hrs

Yes you read that right! – I built an android app with the tools that I know – Visual Studio and in my favorite language C#. Well that’s possible because of Xamarin. In case you didn’t know – Xamarin was founded by nice engineers(Nat Friedman & Miguel de Icaza of Mono fame) who built MonoTouch and Mono for Android which are cross-platform implementations of Common Language Infrastructure (CLI) and Common Language Specifications.

I love C# and it has been the language that I have been associated with all my developer life. So when I thought of developing an app for mobile, I wanted to use the tools that I know rather than go learn something new! Being a C# developer it is quite obvious for me to choose Windows Phone or Windows 8 as the mobile platform to launch my app. But wait a minute, I want them to be built on other shiny platforms too – Who’s gonna build the same app for the famous Android and iOS ? Well I want my app to be used by a million users, if not more! HTML5 based hybrid apps are an option but arguably they aren’t the best fit when it comes to User Experience – at least at the time of writing this post.

Forget all that! – I don’t even want to write HTML5 and JavaScript, I want C#. Yeah!!

Xamarin – Why I love it!

Xamarin let’s you create apps in C# for iOS, Android & Mac. Period.

I had a compelling reason (which I am gonna share with you later) to go write a native android app. So I decided to give Xamarin a try – downloaded the trial version and gave it a shot. And the result – a simple app called TripXpense built in less than 24hrs with no knowledge on Android platform or the way it works! Though it’s a simple app, it would have taken me weeks if I had to build it on Java. Most importantly Xamarin let’s me write in Visual Studio with my favorite plugin resharper running on it. What more can I ask?

Xamarin’s Android API exposes almost 100% of the Andriod’s – that  said you can build a complete android app in C#. I must mention this – Xamarin documentation is a piece of great work from their talented team! They are brilliant!! Honestly, I haven’t even visited the Android SDK Documentation for help.

So what’s the app?

Well it’s TripXpense – a simple app that let’s you add Trips and Expenses. There are only 4 screens and there’s nothing shiny in this app yet because you know it – It’s been just 24hours of the code. If you think you can do better – go fork it from GitHub.


Disclaimer: I am just sharing my experience of an Android Development on this new amazing platform that I love. That said this is no expert material.  Refer Xamarin & Android documentation for patterns and right way of doing things. The code works on my PC & comes with no warranty.

Few Android related stuff that you should know!

Project Structure:


This is how a project structure of an Android app will look. When you create a new Android application in Visual Studio, Xamarin set’s it up for you by default.

Few things to make a note of – only a few for now.


Every Android project must contain this file. The manifest lets you define the metadata of your application like Application Name, Package Name, Required Permissions, Activities etc. This is similar to a App.config or Web.Config files but differs in certain ways. In Xamarin you can easily edit manifest information by going to the properties of the project. Please note that there are other values that are auto generated by Xamarin from the attributes that you define in classes. You can learn more about it from the documentation.


It’s a good practice to keep non-code resources like images, icons, and constants external to your code. Android expects you to store them in a specific sub folders within the resources folder. Notice 6 different Drawable folders which are kept separated based on the DPI displays. These folder will include respective sized bitmaps & PNG images. Perhaps the most powerful Resource to be noted is the Layouts.


Layout is the User Interface – Yes that’s right! Whatever user sees is what is designed inside layout files. These are xml based and have the extension .axml . It decouples the presentation layer – much similar to XAML in Windows Phone.

Here’s an example of a layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:text="@string/Hello" />


Activity is the class responsible for setting the UI content for the users to interact! You can consider this as a code-behind for the Layout written in the resources. So the activity class will contain the presentation logic of your view. It is the class that is referenced by the Android system to do the user interaction. Activities are created or destroyed by the Android system. It’s important to understand the Activity Life Cycle to effectively handle user data in the changing states such as Running, Paused, Backgrounded  & Stopped. For the TripXpense app, I am yet to implement this feature. Here’s an example of an Activity.

namespace HelloXamarin.Android
    [Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
        protected override void OnCreate(Bundle bundle)

           // Set our view from the "main" layout resource

All your Activity classes should derive from Activity base class. Notice the MainLauncher = true set in custom attribute – this is to set the starting screen of your app!
OnCreate() is called when the activity is created. It’s always overridden to perform startup initializations such as

  • Creating  Views
  • Initializing variables
  • Binding static data to lists

Notice the SetContentView() – It places your layout on the screen. Layouts can be accessed using the static variable Resources.Layout.<yourLayoutName>.

Now let’s add a Click event handler to the button placed in the Layout. Shall we?

To get the reference of the button placed in the layout use the helper method FindByViewId<T>() and pass the Id of the button you set in the resource. Once you get the handle – just add the event to the Click handler.

[Activity(Label = "HelloXamarin.Android", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
        private int count = 0;
        protected override void OnCreate(Bundle bundle)

           // Set our view from the "main" layout resource
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };

To navigate to another screen and pass some extra information along, use StartActivity() with an intent that contains the extra information. Extra information is nothing but the data that you want to pass between your screens.

          button.Click += (s, e) =>
                    var intent = new Intent(this, typeof(DetailActivity));
                    intent.PutExtra("userCount", count++);

Finally to receive the extra information that was passed from the previous screen you can use Intent.GetStringExtra or other type based methods. Here’s the full code:

    [Activity(Label = "DetailActivity")]
    public class DetailActivity : Activity
        protected override void OnCreate(Bundle bundle)


            var t = FindViewById<TextView>(Resource.Id.textView1);
            t.Text = string.Format("{0}:{1}","You clicked ",Intent.GetIntExtra("userCount", 0));

Now let’s look at the TripXpense app and few fundamentals of the Xamarin app Development.

TripXpense – built using Xamarin!


TripXpense has 4 screens

  1. Home Screen – that shows list of trips and you can add more
  2. Trip Edit Screen – add and edit trips
  3. Trip Details Screen – displays trip summary and Expenses
  4. Expenses edit screen – add and edit expenses
Cross-Platform development

Xamarin supports cross-platform development in C# but it is not just a write once and run everywhere platform. Because one of its strengths is the ability to implement native user interfaces specifically for each platform. So when you architect your apps make sure you separate the code that is shareable across platforms. Refer Building Cross Platform applications.

Separate reusable code into a core library:

For this app I decided to have my database as xml and created all my classes related to business logic, repository and data access in the core library called TripXpense.Core.  In case I decide to build a Windows Phone, Windows 8 or an iOS app in future, these files don’t have to be duplicated.  And they can be unit tested too! Here’s how it looks:


Please note – You cannot reference this library directly as it is not targeted to Android. And you don’t want to do so because you want them to be accessed by other platforms. Instead you need to use Project Linker extension for Visual Studio which will ensure you have the same code in your Android project. Refer Visual Studio Project Setup Walkthrough

Create an Android Project in the same solution and link the Core project using Project linker. Here’s how your Android project will look with a small blue icon below :


Finally I created the Screens and necessary layouts in Resources and made my app come alive.

Code on Github

You can download this app from my GitHub repository.  Go play around with it and let me know what you think!

Have any questions? Find me on twitter – @nishanil

WPF Datagrid – Update Source on fly with BindingList<T>


I was under an assumption that ObservableCollection<T> works perfect with WPF DataGrid until my friend wannabeegeek came up with a strange problem. The problem was making ObservableCollection<T> update the ItemSource on fly while editing them. What’s the big deal right? Wrong.

If you are using MVVM you do not want to wire up the event on DataGrid for an updated source. You will very much think that as long as you bind the collection to the ViewModel’s property and the mode is set to TwoWay – the source is updated automatically when items are edited in the DataGrid.

Your ViewModel will fire the property changed when the collection itself changes – that is if you replace the property itself.  So if you want to know the change in items of the collection you need to subscribe to the CollectionChanged event of the ObservableCollection<T> property in your ViewModel.

MSDN says:

Occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

But there is a problem with ObservableCollection.CollectionChanged event –  it does not fire when your data item’s property changes. It fires only if the entire item is replaced. That is if you have a collection of an Entity “Expense” that has properties “Name” and “Amount” and if you simply change the Amount value in the grid it does not work! You need to replace the entire “Expense” object for you to see the collection change firing up. 

After googling and reading msdn forums I gave up on ObservableCollection<T> and picked up BindingList<T> to do the job.  Here is a demo that explains all the stuff:

.. and the screen shot:


I have a DataGrid that is simply bound to an “BindingList<Expense>”. Right below that I have a Total that is bound to the “TotalExpense” property. Now here is what I wanted to do – Whenever user edits the amount in the Grid the Total should be calculated as he/she tabs out.

.. and the ViewModel with the solution:

  1. public class DataGridDisplayViewModel : ViewModelBase
  2.     {
  3.         private BindingList<Expense> _expenses;
  4.         private double _totalExpense;
  6.         public double TotalExpense
  7.         {
  8.             get { return _totalExpense = _expenses.Sum(x => x.Amount); }
  9.             set { _totalExpense = value; }
  10.         }
  12.         public BindingList<Expense> Expenses
  13.         {
  14.             get { return _expenses; }
  15.             set
  16.             {
  17.                 _expenses = value;
  18.                 if (_expenses != null)
  19.                 {
  20.                     _expenses.ListChanged += (o, e) => RaisePropertyChanged(() => this.TotalExpense);
  21.                 }
  22.                 RaisePropertyChanged(() => this.Expenses);
  23.             }
  24.         }
  27.         public DataGridDisplayViewModel()
  28.         {
  29.             Expenses = new BindingList<Expense>
  30.                             {
  31.                                 new Expense() {Name = "Gas", Amount = 1000},
  32.                                 new Expense() {Name = "Electricity", Amount = 1000},
  33.                                 new Expense() {Name = "Internet", Amount = 100},
  34.                                 new Expense() {Name = "Water", Amount = 100},
  35.                                 new Expense() {Name = "Misc", Amount = 1000}
  36.                             };
  37.         }
  38.     }

The TotalExpense getter simply calculates the sum. And the ListChanged event of Expenses property simply notifies the change in TotalExpense.

.. and in the View:

  1. <Grid>
  2.     <Grid.RowDefinitions>
  3.         <RowDefinition/>
  4.         <RowDefinition/>
  5.     </Grid.RowDefinitions>
  6.     <DataGrid ItemsSource="{Binding ExpensesOb, Mode=TwoWay}" AutoGenerateColumns="True" Grid.Row="0"/>
  7.     <TextBlock Grid.Row="1">
  8.         <Run Text="Total: "/>
  9.         <Run Text="{Binding TotalExpenseOb}"/>
  10.     </TextBlock>
  11. </Grid>


That’s it!

Download the full code here. The code contains a tiny MVVM framework(inside core folder). – Read the disclaimer of the blog before you play with my code.

If you know to achieve this exact behavior with ObservableCollection do make a comment to this post and let me know!


Attached Behaviors & MVVM

When you think of MVVM and other patterns involved, it is often about separation of concerns as much as possible, unit testability and code maintainability. These type of patterns help in high quality of code and efficient development of business functionality. If you are new to MVVM then you may want to check out some of the articles by various intellects like Josh Smith, Laurent Bugnion and few others from XAML Disciples group(or just Google Smile).

There are lot many frameworks on MVVM out there and to be frank there isn’t any right or the wrong one. You need to evaluate and decide on the one that fits your need! Most often people land up writing one on their own and in a way it is good!

I personally like a framework written by Brette Esterbrooks because it is a skeleton of code that you need and helps you get started. I tweaked it a bit(basically removed the ones that I don’t need) and thus the sample attached on this blog will have a tiny little framework of MVVM.

All it has is just a few helper classes:

  1. ViewBase,
  2. ViewModelBase,
  3. RelayCommand,
  4. ObservableObject.

Attached Behaviors


Attached behavior is achieved by simply attaching a behavior to a control that otherwise wouldn’t have anything of its own.

And as per Josh Smith-

The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.

Ever since I am hooked to MVVM pattern, I try and avoid all the code that usually goes to the code behind. For e.g. a click event handler usually written in the code behind can be omitted and a RelayCommand in the ViewModel be used instead.

But what would happen if you want to handle a double click or a focus event of a control? Just retaining those kind of events to the code behind defeats the pattern itself. And thus Attached Behavior comes to rescue! Demo included in this post explains the DragDropBehavior.

Before you go further with this approach, I just want you to know that you can achieve this by Behavior<T> class included in the However this dll is available only through Expression Blend installation.

In my demo I have explained both of the implementation and it’s usage. Here we go!

Screenshot of the Demo:






The view models can hold the reference of this contract and change at runtime if needed:

  1. public interface IBehavior
  2.     {
  3.         void OnEnabled(DependencyObject dependencyObject);
  4.         void OnDisabling(DependencyObject dependencyObject);
  5.     }



AttachedBehavior – A static class!


A static class AttachedBehavior is introduced which holds the attached properties “Behavior” and “IsEnabled”.

When toggled from Enabled state to Disabled State – OnDisabling() method of the IBehavior is called. Use this method to unwire your event handlers.


  1. /// <summary>
  2.         /// Attach a Behavior of type IBehavior
  3.         /// </summary>
  4.         public static readonly DependencyProperty BehaviorProperty = DependencyProperty.RegisterAttached("Behavior", typeof(IBehavior), typeof(AttachedBehavior), new UIPropertyMetadata(null));
  6.         /// <summary>
  7.         /// Is Enabled, when set to true, fires Behaviors OnEnabled Method
  8.         /// </summary>
  9.         public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(AttachedBehavior), new UIPropertyMetadata(false, OnIsEnabledChanged));
  11.         /// <summary>
  12.         /// Handles IsEnabledChanged
  13.         /// </summary>
  14.         /// <param name="d"></param>
  15.         /// <param name="e"></param>
  16.         private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  17.         {
  18.             if (d == null)
  19.                 return;
  20.             var behavior = GetBehavior(d);
  21.             if (behavior == null)
  22.                 return;
  23.             if ((bool)e.NewValue)
  24.                 behavior.OnEnabled(d);
  25.             else
  26.                 behavior.OnDisabling(d);
  27.         }


DragDropBehavior Class


DragDropBehavior class implements the IBehavior. Have a look at the OnEnabled and OnDisabling methods.

  1. public class DragDropBehavior : IBehavior
  2.     {
  3.         #region Private Fields
  4.         private Point _startPosition;
  5.         private Point _mouseStartPosition;
  6.         private TranslateTransform _translatetransform;
  7.         private UIElement _associatedObject = null;
  8.         private Window _parent = null;
  9.         #endregion
  11.         #region IBehavior Members
  12.         public void OnEnabled(DependencyObject dependencyObject)
  13.         {
  14.             var uiElement = dependencyObject as UIElement;
  15.             if (uiElement == null)
  16.                 return;
  18.             _associatedObject = uiElement;
  19.             //TODO: set the parent accordingly
  20.              _parent = Application.Current.MainWindow;
  21.             _translatetransform = new TranslateTransform();
  22.             _associatedObject.RenderTransform = _translatetransform;
  23.             _associatedObject.MouseLeftButtonDown += AssociatedObjectMouseLeftButtonDown;
  24.             _associatedObject.MouseLeftButtonUp += AssociatedObjectMouseLeftButtonUp;
  25.             _associatedObject.MouseMove += AssociatedObjectMouseMove;
  26.         }
  28.         public void OnDisabling(DependencyObject dependencyObject)
  29.         {
  30.             _associatedObject.MouseLeftButtonDown -= AssociatedObjectMouseLeftButtonDown;
  31.             _associatedObject.MouseLeftButtonUp -= AssociatedObjectMouseLeftButtonUp;
  32.             _associatedObject.MouseMove -= AssociatedObjectMouseMove;
  33.             _translatetransform = null;
  34.         }
  35.         #endregion
  37.         #region Event Handlers
  38.         void AssociatedObjectMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  39.         {
  40.             _startPosition = _associatedObject.TranslatePoint(new Point(), _parent);
  41.             _mouseStartPosition = e.GetPosition(_parent);
  42.             _associatedObject.CaptureMouse();
  43.         }
  45.         void AssociatedObjectMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  46.         {
  47.             var positionDifference = e.GetPosition(_parent) – _mouseStartPosition;
  48.             if(_associatedObject.IsMouseCaptured)
  49.             {
  50.                 _translatetransform.X = positionDifference.X;
  51.                 _translatetransform.Y = positionDifference.Y;
  52.             }
  53.         }
  55.         void AssociatedObjectMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
  56.         {
  57.             _associatedObject.ReleaseMouseCapture();
  59.         }
  61.         #endregion
  64.     }




Attach is the behavior to the control that you want to drag:

  1. <ToggleButton Name="dragDropToggleButton" Command="{Binding ToggleDragDropBehavior}" Width="200">
  2.                 <ToggleButton.Style>
  3.                     <Style TargetType="{x:Type ToggleButton}">
  4.                         <Setter Property="Content" Value="Start Dragging"/>
  5.                         <Style.Triggers>
  6.                             <Trigger Property="IsChecked" Value="True">
  7.                                 <Setter Property="Content" Value="Stop Dragging"/>
  8.                             </Trigger>
  9.                         </Style.Triggers>
  10.                     </Style>
  11.                 </ToggleButton.Style>
  12.             </ToggleButton>
  16.               <TextBlock Background="Gold"
  17.                        Text="dragMe using attached behavior"
  18.                        Behaviors:AttachedBehavior.IsEnabled="{Binding IsDragBehaviorEnabled}"
  19.                        Behaviors:AttachedBehavior.Behavior="{Binding DragDropBehavior}"
  20.                        Canvas.Left="32"
  21.                        Canvas.Top="31" />




And finally the ViewModel that set’s the DragDropBehavior:

  1. public class HelloViewViewModel : ViewModelBase
  2.     {
  3.         private IBehavior _dragDropBehavior;
  4.         private bool _isDragBehaviorEnabled;
  6.         public bool IsDragBehaviorEnabled
  7.         {
  8.             get { return _isDragBehaviorEnabled; }
  9.             set { _isDragBehaviorEnabled = value; RaisePropertyChanged(()=> this.IsDragBehaviorEnabled); }
  10.         }
  12.         public IBehavior DragDropBehavior
  13.         {
  14.             get { return _dragDropBehavior; }
  15.             set { _dragDropBehavior = value; RaisePropertyChanged(() => this.DragDropBehavior); }
  16.         }
  18.         public RelayCommand ToggleDragDropBehavior { get; set; }
  20.         public HelloViewViewModel()
  21.         {
  22.             DragDropBehavior = new DragDropBehavior();
  23.             ToggleDragDropBehavior = new RelayCommand(() =>
  24.             {
  25.                 IsDragBehaviorEnabled = !IsDragBehaviorEnabled;
  26.             });
  28.         }
  29.     }


That’s It – you are done!! Refer DragDropBehavior2 class for implementation using Behavior<T>.

Download the Code – Read the Disclaimer of this blog before you work with this code!