WPF Tip: Collection Changed Event

Hi, quick tip for WPF. I’m set to leave for my 2 week vacation today, so this will be a quick one.

I was building a physics simulation in WPF (still to be completed), and as usual I binded my ObservableCollection to a Custom Canvas control, which I specified in my ItemsControl‘s ItemPanelTemplate. If you have noticed, all the WPF “container” controls like ListBox, ItemsControl, etc all have an ItemsSource propery where you can specify your data source. So what happens when I add/remove something from that data source, how do I get notified???

I did some digging around, but realised there’s no such event that gets triggered. The trick is to look at the the Items property, which is of type System.Windows.Controls.ItemCollection. It inherits from a CollectionView, which implements the INotifyCollectionChanged interface, which has the CollectionChanged event. Bingo, here we go…

This is sample code that demonstrates how to use this.

public Window1()
    ((INotifyCollectionChanged)itemsControl.Items).CollectionChanged += new NotifyCollectionChangedEventHandler(Window1_CollectionChanged);
    itemsControl.ItemsSource = particles;

void Window1_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    if (e.Action == NotifyCollectionChangedAction.Add)
        // do something

So you will now be notified of changes in your control’s Items due to changes in your data source. You might also want to learn more about the NotifyCollectionChangedEventArgs, it has some useful properties in there. Also you should have a look at NotifyCollectionChangeAction enum values to learn more about what kind of notification actions are available.

Share this post :
Posted in WPF. Tags: . 3 Comments »

Harvesting Your Brain

The human brain is a fascinating “device”, which allows us to function and makes each of us unique. It’s our Central Processing Unit (CPU), and unlike the CPU in our computers, we cannot replace our brain with a faster one. So then how do we evolve and make our CPU run faster and more efficiently? I guess nobody has that definite answer yet, but I got some clues about improving the way we think / solve problems / generate ideas from one of my favorite books, Refactor Your Wetware. (btw, this is a great book, do read it.)

Consider the image below, which I find is a funny metaphor of our brain (borrowed from the book).


Read the rest of this entry »

WPF: Auto Arrange Animated Panel

My attention has been diverted as of late, from WPF commands to trying to create something cool in WPF. I’ve been greatly inspired by Kevin Moore, with his WPF Bag of Tricks, especially his cool animated panel that can rearrange things inside. I looked through the code, and there were many things I did not understand. Being fustrated, it was a perfect opportunity to learn something new, at the same time building something fun. After all programming should be fun. 🙂

Before I start talking about specifics, let’s look at the UI for this sample.

arrangepanel1 Please have a look at the demo video, I’m sure some of you will enjoy this.

The essential part of this sample is in the custom ArrangePanel class inherited from System.Windows.Controls.Panel. Before we go into that, there are some interesting things about WPF’s layout mechanism you should know about. WPF booasts a dynamic layout mechanism where controls should not be statically placed on the Window/Page, like how we tranditionally do in WinForms. The controls in the visual tree “talk” to each other before they decide how to lay themselves out . This happens in the FrameworkElement‘s MeasureOverride and ArrangeOverride methods. Here’s an illustration of this intent.

Read the rest of this entry »

Posted in WPF. Tags: . 5 Comments »

WPF Commands Part 3: Custom RoutedUICommand

Welcome to Part 3 of WPF Commands. This will be the second last of the Basics for WPF Commands. For this entry, we will be looking at creating a custom RoutedUICommand, and how to make use of CommandTarget and CommandParameter properties.

First of all, you will typically need to create custom commands if the ones you get out of the box from WPF is insufficient. I would not think that this is a common scenario, but it would be good to know how to do it. If you need to do this, I recommend putting your custom controls into a separate class, similar to WPF. Let’s call our custom class CommandLibrary.

public static class CommandLibrary
    private static RoutedUICommand add = new RoutedUICommand("Add", "Add", typeof(CommandLibrary));

    private static RoutedUICommand remove = new RoutedUICommand("Remove", "Remove", typeof(CommandLibrary));

    public static RoutedUICommand AddListItem
        get { return add; }

    public static RoutedUICommand RemoveListItem
        get { return remove; }


Read the rest of this entry »

WPF Commands Part 2: Command Bindings and Gestures

Welcome to Part 2 of WPF Commands. If you have not looked at my previous entry talking about the basics, you should have a look at it here. That should set you up for understanding this example.

What are Command Bindings? Simply put it, it allows us to specify the commands that a particular control will be listening to, and the event handlers that will implement the command logic. If you remember that all commands in WPF implement ICommand interface, it defines two methods CanExecute and Execute. Controls (ones that can handle input focus) typically understand how to execute commands on themselves. So now, how do we “make” a control understand a different command?

For example, I want to be able to make a TabContainer change tabs on a button click. How do we achieve that? No brainer here, with Command Bindings. To make it more exciting, WPF also allows us to hook up commands with Input Gestures. It’s an abstract class, and we will be dealing with two types of gestures, namely KeyGesture and MouseGesture. Examples of mouse gestures are left button click, scroll wheel click and key gestures speak for themselves. Both kinds of gestures allow us to also define an optional control modifier, e.g. Control + Left Button Click, or Shift + C key. A Command Binding allows us to wire up a control to a custom Command, or WPF’s library of Commands, or Input Gestures.

The sample application will be the same as my previous post, but we will be using the Buttons and key gestures to navigate between the tabs on the Tab Container. Please take a look at this video of this demo.


Read the rest of this entry »

WPF Commands Part 1: Basics

WPF has introduced to us developers a wide new range of concepts and useful features, one of which is the Command System. It is based on the infamous Command Pattern, with a slight twist. It’s basically utilizing the Command Pattern with routing facility, as termed by Microsoft as the Routed Command System. Examining this closely, it’s similar to the Routed Event system that is inherent in WPF, and they used it for sending Commands for the UI controls to trigger a certain behaviour.

In one of my previous projects using WinForms and Model-View-Presenter (MVP) pattern, we faced the challenge of implementing a TreeView that is capable of triggering certain behaviours at different TreeNode Presenters. One of the developers came up with a very interesting implementation of using the Command Pattern and a variation of the Visitor Pattern. It was complicated, being a fresh developer, it took me hours to understand. Later he told me this pattern he used is known as the Double Dispatch pattern, which I later read about in a Design Pattern book. Now looking at Routed Command has reminded me of this, and is a similar implementation of the Double Dispatch.

It’s very interesting to see that Microsoft has started using a lot of Patterns in WPF, like Command and Observer. MS has also introduced a slight varation of the MVP, called Model-View-ViewModel pattern alongside the Pattern and Practices guide. In my opinion, this is a breath of fresh air, and .NET developers can no longer be “excused” from knowing about using and understanding patterns and how it helps to write elegant code, and decoupling your application.

Read the rest of this entry »

Using Dependency Property and DataBinding in WPF

For some reason, I started looking at Windows Presentation Foundation (WPF) again. I read a book on WPF a while back, it’s a very interesting but has a very steep learning curve (for me anyways). One of the things I did not get about WPF was this new property system called Dependency Properties (DP). I read that the WPF team built this on top of the CLR because they found the existing Property system to be inadequate.

In a nutshell, the DP system is a radical extension to the normal getter/setter Property system we are so familiar with. The interesting thing about DP is that it’s value is not pre-determined, but always resolved, dynamically at run-time, based off a set of rules.

Read the rest of this entry »

Posted in WPF. Tags: . 5 Comments »