Implement dependency properties

May include but is not limited to: enabling data binding and animation, property metadata, property change callbacks

WPF adds a new concept to the classic .NET property world, namely dependency properties. They introduce some nice new features such as property value inheritance and change notification. You can imagine that most of the WPF properties are dependency properties.

Like almost anything else, dependency properties are coming in multiple variations. The first is a “simple” dependency property, and the second is an attached dependency property. More info about the latter is in the end of this post.

What do we need to define a classic dependency property (that is not an attached one)? Three things:

  • defining the property
  • registering it
  • wrapping it within a normal .NET property

Well, that doesn’t sound like a big issue, so let’s define one!

First we need to define the property – in the class we’ll use it in. To do so, we need to add a static field of type DependencyProperty (this field might be shared with other elements, so it’s a good point to define it as static). Also, you need to define the field with the readonly keyword, so it can only be set in a static constructor. The whole code might look as follows: Continue reading


Implement drag and drop operations within and across applications

Dragging and dropping pieces of information is fun. Sometimes I do it too – maybe once a week, maybe twice. The point is that you can do it in WPF, and as the title says: within and across applications.

Let’s see a fairly basic example: drag something and drop it to another control. First we need to handle the MouseDown event on the source control (you must hold down the mouse, move it to another place, and release it there). We need a method there:

private void source_MouseDown(….)
Label lab = (Label) sender;
DragDrop.DoDragDrop(lab, lab.Content, DragDropEffects.Copy);

Then you need to handle the target’s drop event, like this:

private void target_Drop(object sender, DragEventArgs e)
 ((Label)sender).Content = e.Data.GetData(DataFormats.Text);

These code samples were from the book Pro WPF 4 in C# 2010.

Of course you could improve this drag and drop experience to check whether or not data is present before “dropping” it on the target. There’s an event just for that, and it’s called DragEnter. A perfect candidate to check things like the format and the availability of the data to be dropped.

If you’d like to drag and drop across applications, then I have a nice link for you. It’s a little code written by Scott Garland who seemed to be a little upset when he tried to do the thing. Anyway, don’t give up the hope – you need a class implementing ISerializable or IDataObject to begin with, and the rest will be simple…