Andy's observations as he continues to attempt to know all that is .NET...

Wednesday, October 10, 2007

WPF Extension method

I used my first extension method yesterday with WPF.  I wanted to bring a control to the foreground, that means changing its position in the child list to the last child.


 

  Parent.Children.Remove(element);

  Parent.Children. Add(element);


 

What I would prefer to do is call SendToFront on the collection with the appropriate child.  Since I don't have any control over the type being used to hold the collection,  I would need to resort to extension methods to get a more object style syntax.  Resulting in the following code.


 

public static class UIElementCollectionExtensions

{

   public static void SendToFront(this UIElementCollection collection, UIElement element )

   {

        collection.Remove(element);

        collection.Add(element);

    }

}


 

All this is well and good but it would have been virtually as elegant with an old fashioned static call on some Util class.    It then dawned on me why these are perhaps so useful, for me anyway I rely on intelli sense to see what I can do with a lot of the WPF controls, with any Util class methods I write I need to have knowledge of them, but with extension methods intelli sense can potentially pick them up.  So I refactored my code once more into a separate assembly, but placing the code into the System.Windows.Controls namespace, thus whenever I use WPF controls and reference my additional extension assembly I get my new methods.  On a large scale project I can see how this could be aid productivity.


 

However there is something smelly about placing my code into someone else's namespace so on reflection I think it would be far nicer to place all my extension methods inside my own namespace, and just make sure I bring them into scope by using my extension namespace.

No comments:

About Me

My photo
Im a freelance consultant for .NET based technology. My last real job, was at Cisco System were I was a lead architect for Cisco's identity solutions. I arrived at Cisco via aquisition and prior to that worked in small startups. The startup culture is what appeals to me, and thats why I finally left Cisco after seven years.....I now filll my time through a combination of consultancy and teaching for Developmentor...and working on insane startups that nobody with an ounce of sense would look twice at...