Visual Studio 2008 offers many usefull tools for aiding you in debuging your application. Among all the most interesting are: Watch, Call Stack, Immediate Window and the ability to set a conditional breakpoint in your code. These are really briliant features that lets you find and fix bugs in a very short time. There are some situations however, when this is not enough.

GUI development heavily relies on events. Often after launching an application or changing some property of some control, the whole army of different events is being launched, calling each other. This is really confusing for the developer. You set SelectedIndex of some grid control in the construtor of the class, but the value of this property is changed several times after this control finally repaints itself. How to figure out what causes this property to change value? You cannot just set a breakpoint inside setter for this property, as this code comes from *.dll and is not accesible. The answer is included in this short article and consists of several steps. Unfortunatelly it only works for dependency properties.


Step 1:

Declare field of type System.ComponentModel.DependencyPropertyDescriptor in your class:

DependencyPropertyDescriptor _selectedItemDescriptor = null;

Step 2:

Initialize this field using FromProperty method pointing to the property which is supposed to be observed:

selectedItemDescriptor = DependencyPropertyDescriptor.FromProperty(DataGridControl.SelectedItemProperty, typeof(DataGridControl));


Step 3:

Assing a method which is to be called when the value of this property changes:

_selectedItemDescriptor.AddValueChanged(datagridMain, PropertyChangedDelegate);


This method must have a standard signature that EventHandler defines:

void PropertyChangedDelegate(object sender, EventArgs e) {...}

And this is it! Works for every dependency property and will fire as many times as the value of this property changes. Now you can easily wait for the call that will assign for this property some "magic" value and track down the method that caused this change using CallStack tool.