Analyzing the visual tree in F#

October 30, 2007

I finally had my first “Aha!” moment with F# today.  After reading Robert Pickering’s amazing article about Erlang style message passing in F# I tried to create a very dumbed-down version of a function he created.  I wanted to create a function which counts how many instances there are of each type of element in a Window’s visual tree.

I’m using the WPF visual tree as a data structure to program against.  Since I can easily configure a visual tree via XAML, it makes for an excellent way to create a tree structure of diverse data types.  VisualTreeHelper is used to traverse that tree of elements, by calling its GetChildrenCount and GetChild methods.  This brings me to my “Aha!” moment…

In my previous post I recursively walked the visual tree by using a for loop, just like I would in C#.  But today that felt wrong.  I forced myself to drop my old habit of manually looping, and try to think about things differently.  As it turns out, F# makes it really easy to recursively walk down trees by using something called a “list comprehension.”  I used that feature to “declare” that I want a list of every child element of a given element, then I forward that list to the List.iter function.  The callback passed to List.iter contains the recursive call!  Check out the code in the countTypes function, where the comment reads “// Process this element’s children.”

Analyzing the visual tree in F# (code)

The output of running the demo application contains the output of two functions.  The countTypes function output is listed second, as seen below:

Analyzing the visual tree in F# (output)

I’m starting to really enjoy programming in F#.

Download the demo app here: Analyzing the visual tree in F# (demo project) Be sure to change the file extension from .DOC to .ZIP and then decompress the file.  Download the F# compiler and tools here.


Walking the visual tree in F#

October 29, 2007

This blog post shows how to dump the visual tree into a console window, using F#.

In my continued quest to understand how F# and WPF can work well together, I wrote a simple utility which walks down the visual tree of a UI and writes it out to a console window.  I found that F# is a natural fit for this type of quick script-like coding.  This app is not imminently useful, but it is a great way to both learn F# and get used to manipulating WPF with F#.

Here is the F# code:

Walk visual tree in F# (code)

Notice in the ‘createWindow’ function it uses the ‘use’ keyword.  That is a relatively new addition to the language, which you can read more about here.  It’s like a ‘using’ block in C#.

When the app runs, it loads a Window from a XAML file.  That XAML looks like this:

Walk visual tree in F# (xaml)

When you run the app, you will see both a console window and the window which was loaded from the XAML file.  Here is a screenshot:

Walk visual tree in F# (screenshot)

Download the demo app here: Walk visual tree in F# (demo app)  Be sure to change the file extension from .DOC to .ZIP and then decompress the file.  Download the F# compiler and tools here.

Karl Shifflett Rocks

October 28, 2007

A while back I posted an article to CodeProject called The WPF Thought Process.  In that article I explained how to implement a feature which adds selection indicators to ListBoxItems.  Just recently Karl Shifflett (the world’s most gung-ho WPF disciple) wrote a response to my article, where he shows two alternate ways to implement similar functionality.

His article shows how to implement ListBoxItem selection indicators and a CheckListBox control.  One of his approaches is 100% XAML, and the other is a custom control.  I highly recommend checking it out.  Karl packed his article with a lot of interesting information about WPF, and his techniques for solving the problems are very imaginative.  Great work, Karl!

The Infragistics Tangerine Exemplar

October 26, 2007

I took today off of work to celebrate my birthday and relax a bit.  Ya know, enjoy some coffee, Mahler symphonies, WPF, Glenn Gould playing Bach, F#, etc.  The good life!

I finally found some time to dive into something which has been on my todo list for a while.  Infragistics has a User Experience Group which is responsible for creating something they call “exemplars”, which are basically reference applications that show how to use their controls in a real-world application.  To learn more about what an exemplar is, read about it here.

They recently released an exemplar called Tangerine.  This application is an asset browser, which allows you to view data from Amazon Web Services, or any other data provider you want to plug in.  It uses their WPF controls in the presentation layer, and uses Microsoft’s Enterprise Library for things like logging and exception handling.

It’s all about showing how to use best practices to create a realistic WPF application. The application lets you search through various types of products on Amazon, and view information about them.  The performance is good, and usability is intuitive.  Not only that but it looks really, really cool because they had a visual designer Blend some magic pixie dust into it.

The code seems top-notch so far, from what I’ve seen.  Tangerine definitely has a lot to teach anyone interested in working their way through it.  In addition to the great code, the solution comes with truly superb documentation.  I’ve read through three of the documents so far (“Introducing Tangerine”, “Story”, and “Architecture”) and was amazed at the quality of the writing.  I can’t believe Infragistics is just giving this stuff away for free.

You need to install their NetAdvantage for WPF product to run Tangerine.  You can download the free trial of their WPF product if you just want to give it a whirl for free.  I highly recommend checking this out.  I’ve spent only a few hours reviewing it so far, and have already learned a lot of interesting things to consider when designing and developing WPF applications.  And, it’s free!!  That’s quite a birthday present! 🙂

Logging Routed Commands in F#

October 25, 2007

In my previous post I showed how to set up a generic technique for logging details about the execution of routed commands in a Window. That post’s demo app was written in C#. I’m trying to learn F# and explore how well it works as a language with which to program WPF applications, so I decided to re-write that demo in F#. Since I’m not at all proficient with F# yet (I’ve been studying it for less than a week), I had to drop a few aspects of the original demo simply because I have no clue how to implement them in F# yet!

If you want to run this demo app, you need to install the F# distributable. I am using version, which is available here. It can work with Visual Studio 2003, 2005, and 2008.

Here’s the Window1.xaml file:

Command Logging in F# (xaml)

Here’s the F# code (demo.fs):

Command Logging in F# (code)

If you compare this code with the C# code in my previous post, it’s immediately clear that we’re in a different world here. I cannot pre-compile my Window1 class into a BAML resource because F# projects have no notion of that. Instead I must load the XAML file from disk and pass it to XamlReader.Load to get the Window instantiated (that useful little function came from Robert Pickering’s book “Foundations of F#”). This also means that I cannot have a code-behind file for the Window1 class, unless there’s some trick I’m not aware of yet.

All of the code contained by the Window in the C# version now lives outside of it, because Visual Studio won’t let me have an F# code-behind file at this point in time. Eventually that might be addressed, but for now it kind of throws a monkey wrench into the whole “encapsulation” thing.

I really like how the calls to CommandManager functions in the attachedCommandLogger function are set up. The syntax for passing an anonymous function in F# is very nice, and I look forward to using the similarly elegant lamba syntax in C# 3.0 too. Since F# influenced many of the modern additions to C#, learning F# feels like killing two birds with one stone.

Programming in F# just feels “light” somehow. I like it.

I don’t think that this demo is in-depth enough yet to persuade me either for or against using F# with WPF. Once I have a better grasp on the language, and the concepts, I will be able to make a better decision about that. Until then I’m just enjoying WPF and F#!!

You can download the demo app here: Command Logging in F# (demo app) Be sure to change the file extension from .DOC to .ZIP and then decompress the file.

Logging Routed Commands

October 25, 2007

This blog post shows how to log details about any routed command being executed in a Window. The technique only works with routed commands because it depends on the CommandManager’s tunneling PreviewExecuted attached event to notify the Window of command execution.

Suppose you have a Window with many controls in it and you want to figure out when any routed commands are executed, perhaps for debugging or usage analysis purposes. How might one do that?

The technique I came up with depends on the CommandManager class to notify the Window whenever a routed command in that Window is executed. I establish a listener on CommandManager’s attached PreviewExecuted event and let that tell me everything I need to know.

Here’s the Window’s code-behind:

Command Logging (code)

Here’s the XAML, which contains a few Buttons with their Command property set:

Command Logging (xaml)

After I run the application and click each Button once, the log file (which is really just text in the Output window in VS) contains this:

Command Executed @ 10/25/2007 7:38:00 PM
  Name=Open; Parameter=; Source=System.Windows.Controls.Button: Open Sesame!
Command Executed @ 10/25/2007 7:38:01 PM
  Name=Close; Parameter=; Source=System.Windows.Controls.Button: Close Sesame!
Command Executed @ 10/25/2007 7:38:02 PM
  Name=My Routed Command; Parameter=fooParam; Source=System.Windows.Controls.Button: My Routed Command!

Notice that the “My Normal Command!” Button’s command does not appear in the log. That is because the MyCmd command is not a routed command, but simply a class which implements ICommand. Only the execution of RoutedCommand objects are logged.

Download the source code here: Command Logging (demo app) Be sure to change the file extension from .DOC to .ZIP and then decompress the file.

WPF in F#

October 24, 2007

My blog has been quiet these days, for a few reasons, but mostly because I am excited about learning F#. In case you have never heard of it, F# is a new language being developed by Microsoft Research. Somasgear recently announced that Microsoft is investing heavily in F# and plans to make it a first-class .NET language, giving it full support in Visual Studio.

I was raised on C-based languages: C, C++, and C#. The concepts and syntax in F# are radically different from anything I am used to because it is largely influenced by OCaml, which is a functional programming language. F# is a hybrid of functional, object-oriented, and imperative programming languages.

Traditionally functional programming has been used for math-intensive programming problems; like financial analysis, and scientific computing. I’m not interested in learning F#, or functional programming, for that reason. What I want to know is if F# can be useful in the area of WPF programming, or, more generally, in front-end development. Are there sweet spots where F# and WPF will work together much more naturally and less verbosely than, say, C# and WPF? If so, what are those sweet spots and how can I introduce F# into my normal development workflow? If not, why not?

Robert Pickering, the author of the only F# book currently on the market, has posted some entries on his blog which use WPF and F# together. They’re not particularly useful examples, but interesting nonetheless. You can find them here and here.

Do you have any experience using F# and WPF together? If so, I’d love to hear more about it.

Great time at Charlotte Code Camp

October 21, 2007

I spent the weekend in Charlotte, North Carolina and had a great time giving my WPF presentation at the Charlotte Developers GUILD Code Camp.  I met a lot of really nice people down there, and found that there was a lot of interest around WPF amongst the attendees.  It was a blast!

I had the pleasure of meeting and hanging out with the most passionate WPF developer and speaker in the known Universe, Karl Shifflett.  Karl gave his impassioned WPF presentation after mine, and did an awesome job.  I think I convinced Karl to start sharing his passion for WPF and VB.NET by blogging tips and tricks, which should help fill that gigantic WPF/VB.NET abyss in cyberspace.

Also I got to meet Rob Zelt, the man who once made my day when he sent me a PDF copy of my old blog, which had been deleted by my previous employer.  Thanks Rob!

The Danger of Assigning Event Handlers in XAML

October 16, 2007

I recently discovered a nasty little “WPF gotcha.”  This issue makes me question whether one should ever hook events of an element in XAML.  Basically the problem arises if you hook an element’s event in XAML, set a property of the element which will cause the event to be raised (also in XAML), and in the event handling method reference another element which is declared after that element.  You will find that the reference to the other element is null, because the BAML deserialization process hasn’t gotten around to creating that other element yet.

Here’s a stupid example which shows the problem in action.  It allows you to pick a word from a ComboBox, and then displays that word in reverse on a TextBlock beneath the ComboBox.  The SelectionChanged event of the combo is hooked in XAML so that we can execute the code which reverses the text and display it on the TextBlock (in a real application this type of data manipulation should be done in a value converter).  Also note that the ComboBox’s SelectedIndex is set in XAML, which causes the SelectionChanged event to be raised during the BAML deserialization process.

EventHandlersInXAML (markup)

Here’s the OnComboSelectionChanged event handling method, which is referenced in the XAML seen before:

EventHandlersInXAML (handler)

To fix the problem, we can remove the event handler assignment from the XAML and replicate it in code, as seen below:

EventHandlersInXAML (ctor)

You would also have to execute the logic which transfers the reversed text to the TextBlock at some point as the Window loads, to handle the initial value of the ComboBox.

Other ways to fix the problem include: set the ComboBox’s SelectedIndex property after the call to InitializeComponent in the constructor, or declare the TextBlock above the ComboBox in XAML, etc.

Download the demo application here: EventHandlersInXAML (demo project)  Be sure to change the file extension from .DOC to .ZIP and then decompress it.

An article about the WPF thought process

October 13, 2007

I just published an article entitled “The WPF Thought Process” on CodeProject. This article is different from all of my others because its primary focus is on the various thoughts that passed through my mind while implementing a feature, instead of just focusing on how it works. I hope that this article proves useful to people who are trying to get into WPF, but find the conceptual model a bit strange or confusing. The article walks you through various stages of figuring out how to design a ListBox with custom selection indicators. If you’re interested in reading it, here’s the link: