The Missing .NET #3: An AutoComplete TextBox in WPF, Part 2 – Making it reusable

The .NET framework is huge, but not so huge that it does everything for everyone; there are things that they in Redmond miss or don’t do for whatever reason but is still generally applicable to many developers. So, dear reader, I present to you a new series of posts on stuff I find missing in .NET, typically where even the Google fails to find the answer. It could be a useful class, a technique, a good practice or documentation that should be in the framework but isn’t.


In Part 1 last time, I started creating an AutoComplete TextBox in WPF using only the controls given to us by Microsoft and the concepts of WPF. I showed how you can quickly get the meat of the problem solved using a custom ICollectionView that filters based on the text in the TextBox. In this part, I’ll discuss what’s needed to make it reusable.

Reusa-ma-bility

Alright. So we have a pretty good idea of what’s required, how are we going to package this up to be reused elsewhere? Right now, my implementation is good for the window that I implemented it in. I could make a new control, and add this logic to it, but I already said at the outset that that wasn’t going to happen.

What I decided to use was an attached property. The guidance on using Attached Properties was what finally sold me. See, I also want to use this on ComboBoxes eventually, but ComboBox and TextBox, which both have a Text property, don’t have a common ancestor past Control. One of the scenarios that the docs describe, but don’t provide an example of is wanting to have a property on different, unrelated parts of the control hierarchy. I don’t know why Microsoft can’t provide an example, but I can: the TextSearch class defines two attached properties with this scenario in mind. (Seriously, the docs for .NET 1.1 were awesome. What the hell happened to msdn?)

OK, so I’m going to use an attached property. What that looks like is the following:

public sealed partial class AutoComplete
{
  public static readonly DependencyProperty SourceProperty;

  static AutoComplete()
  {
     SourceProperty = DependencyProperty.RegisterAttached("Source",
                        typeof (object), typeof (AutoComplete),
                        new FrameworkPropertyMetadata(null,OnSourcePropertyChanged));     
  }

  public static object GetSource(DependencyObject o)
  {
     return o.GetValue(SourceProperty);
  }

  public static void SetSource(DependencyObject o, object value)
  {
     o.SetValue(SourceProperty, value);
  }
}

This is pretty standard stuff that you can find in the docs. The one piece that’s missing in that snippet is the event handler method OnSourcePropertyChanged that’s declared in the call to DependencyProperty.RegisterAttached. I’ll get to that in Part 3.

What this allows is I can use this on any DependencyObject, like so:

<StackPanel >
    <TextBox Name="textBox1" 
         local:AutoComplete.Source="{Binding Source={StaticResource people}}"
         VerticalAlignment="Top" 
         HorizontalAlignment="Stretch" 
         TextChanged="textBox1_TextChanged" />    
</StackPanel>

where local is my declared namespace for my assembly (Visual Studio does this for you).

Awesome. I can put this on a ComboBox now, or anything else that allows text input. Now we have an auto-completing TextBox. Your welcome.

Yes, you have a question? There’s some parts missing? Like what? Oh, right the ListBox, it’s not there anymore.

A Look-less Autocomplete TextBox

I’ve already solved the hard problem of getting the List to show up when the user types something; I just need to make that work on any TextBox. The trouble is, I’m manipulating the visual tree, which, to my belated discovery, is really hard to do in code after the TextBox is created. Turns what I want to do is create a ControlTemplate that contains my ListBox and replace the TextBox’s Template with my own.

One of the key concepts in WPF is what the folks at Microsoft call "look-less controls". The canonical example is the button. There are a bajillion — at my last count — samples of making buttons look different than the standard Windows button in WPF. They do this by manipulating either the Content property of the button, or its ControlTemplate. Either way, you still have a button that can be clicked, but you’ve changed the look of the button. All WPF controls act like this, more or less, to some degree: I was asked to make a ListBox turn into a TabControl and that’s non-trivial, nigh impossible, even though they are related in the control hierarchy.

Another example is the ComboBox. I mentioned in the first edition of The Missing .NET that the traditional Win32 ComboBox is made up of three controls: a button, a listbox, and a textbox. Well, so is the WPF ComboBox! Only, the WPF is a little more explicit about it, and more flexible. The place where this is done is the Control.Template dependency property; it’s a dependency property hanging off Control that lets you set the visual tree of your control. The standard controls manipulate this property in their default Style. One tool you want in your WPF developer toolbox is something that will deconstruct the default Styles of the standard controls; I use XamlpadX. Bombing around the styles should give you an understanding of how they work.

Deconstructing the ComboBox in XamlPadX, sure enough, we see the TextBox, the ToggleButton and the ItemsControl, of which ListBox is a descendent.

We’re getting into some seriously advanced, yet fundamental WPF stuff here, which is a little beyond the scope of this blog post, at least if I wanted to finish quickly. If you’re interested in learning about Templates and Styles, Google can be big help; if you’d prefer to learn offline, then any of the WPF books will be quite helpful. Start small, and work your way up. Learning how templates and styles work is definitely worth the effort.

So the only way to stick my ListBox into the visual tree is to replace the ControlTemplate of the TextBox.

This is where the internets came up short for me and I went out on my own. I have no idea if my solution is a good idea. It seems to work, and work well, but I don’t know enough about WPF to tell if this will work in every situation. Every solution creates its own problems and I ran into a few while solving this one.

OK, so what did I do?

You’ll have to wait ’til next time. πŸ™‚

The Missing .NET #3: An AutoComplete TextBox in WPF, Part 1 – A rough first draft

The .NET framework is huge, but not so huge that it does everything for everyone; there are things that they in Redmond miss or don’t do for whatever reason but is still generally applicable to many developers. So, dear reader, I present to you a new series of posts on stuff I find missing in .NET, typically where even the Google fails to find the answer. It could be a useful class, a technique, a good practice or documentation that should be in the framework but isn’t.


The more I use WPF, the more I’m impressed and confounded by it. Impressed because it is really well-designed, thoughtful, and quite rich right out of the gate; I’m confounded by the things it’s lacking. I realize they had to ship something sooner than later, but some of the things Microsoft left out seem pretty trivial to implement given what I know about WPF. One of these is an auto-completing TextBox (It was even late to the Windows forms party, but still…). The most famous example is the address ComboBox in the browser. Start typing to see that the computer remembers what you typed previously. Auto-complete is everywhere in the OS, and you can see it on the web in spots too, now: Compose a message in Facebook and you’ll see your contact list drop down and filter out as you type.

I’ve seen suspiciously little from The Google on auto-completing text boxes using WPF. This can lead me to possible two explanations:

  1. Auto-complete is obviously trivial and so everyone just implements it in two lines in their own projects, and I’m a complete idiot for searching The Google in the first place; or
  2. No one is using WPF for anything  usable with normal-looking controls — they just want the 3-D light show with lasers.

In either case, I figure I’ll just keep writing this post. There are definitely more complete idiots out there, if 1 is the case. If 2 is the case, I just have to wait a few months or years for this post to be relevant.

When I set out, I had a goal to make a TextBox with auto-complete, I was going to use WPF’s idioms to the fullest, meaning no custom controls or inheriting from TextBox to add what I want. Also, I detest making custom controls because they are so hard to maintain and they aren’t just there in the IDE to use, like the default controls; the case would have to be pretty compelling to replace something as fundamental as the text box, and autocomplete ain’t it.

Besides, I think it’ll be a rare thing to create a custom control in WPF, at least a custom control the way a WinForms developer would think about a custom control: there’s just too much you can do with element composition and templates in WPF.

After some digging, I noticed that the bits and pieces of AutoComplete are already there in WPF; all I had to do was stitch them up together in a nice little package. So what I’d like to do is talk about those parts before I explain how I made the control. In the first part, I’ll talk about filtering the list as the user types; you know, the part that gives a textbox its autocomplete-y-ness.

List-Filtering: CollectionViewSource

People like lists in their blog posts I’ve found; so here’s a list: the Best Thing about WPF

  • Data-binding

The end.

You can write an RSS reader in like 100 lines of XAML and zero lines of code, all with data-binding. Representing custom classes is a matter of a moment, creating a DataTemplate for them. Hierarchical data? No problem. XML? No problem. Database? Um, not sure, don’t use ’em, but probably.

WPF was designed with data-driven apps as one of the key scenarios, and it shows. What’s even nicer is that you can get started right away without knowing too much about how databinding works. But dig a little deeper and you can see how well-designed it is.

For instance, the ListBox can represent a list of items and, with DataTemplates, you can customize the look of each item. You can also track the currently selected item and bind other controls to that item. What if you had two ListBoxes, though, both pointing to the same collection, and you wanted one to show a subset of the collection? Could you do that?

Absolutely.

When you bind to a list source WPF wraps the source in an ICollectionView. The ICollectionView manages the currency (the currently selected item) of the list for the ListBox. Each ListBox gets a different ICollectionView instance. If you look at the API for ICollectionView, you’ll see some methods and properties for grouping, sorting, and filtering.

We’re interested in filtering lists! If you want to filter a list, you can create your own ICollectionView through it’s XAML representation, CollectionViewSource; bind it to your source; bind your list box to your CollectionViewSource and then register for the Filter event on the view.

The XAML below provides an example of this.

<Grid Name="grid1">
     <Grid.Resources>
        <ObjectDataProvider x:Key="people" 
                            ObjectType="{x:Type local:People}" 
                            MethodName="GetPeople" />
        <CollectionViewSource x:Key="viewSource" 
                              Source="{StaticResource people}" 
                              Filter="CollectionViewSource_Filter"/>
    </Grid.Resources>
    <ListBox ItemsSource="{Binding Source={StaticResource viewSource}}" />
</Grid>

The CollectionViewSource_Filter event handler is where your filtering code goes. If you hook it up in XAML, you get a nice event with specific event args, but you could also do it in code, in which case, the Filter property is a Predicate<T> delegate. The event deals with each item in the data source at a time.

So where am I going with this ICollectionView thing? Well, if you look at what constitutes an autocomplete textbox in Win32, it’s a just a textbox with a listbox below that shows up when typing happens and filters the items in the list based on what’s typed.

So why not start there in WPF?

Autocomplete TextBox First Draft

My first iteration wasn’t a control or anything more complicated than the XAML below

<StackPanel >
    <TextBox Name="textBox1" 
         VerticalAlignment="Top" 
         HorizontalAlignment="Stretch" 
         TextChanged="textBox1_TextChanged" />
    <ListBox Name="listBox1" 
         Visibility="Hidden"
         ItemsSource="{Binding Source={StaticResource viewSource}}"
         HorizontalAlignment="Stretch" 
         Focusable="False"/>
</StackPanel>

The viewSource in the ListBox.ItemsSource Binding is the same as the previous XAML snippet. In the code behind file, I have the following event handlers:

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    CollectionViewSource viewSource = (CollectionViewSource) grid1.FindResource("viewSource");
    this.listBox1.Visibility = this.textBox1.Text != "" 
                                    ? Visibility.Visible : Visibility.Hidden;

    viewSource.View.Refresh();
}

private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
{
    e.Accepted = e.Item.ToString().StartsWith(textBox1.Text, 
                        StringComparison.CurrentCultureIgnoreCase);
}

When the text changes, I ask the viewSource’s ICollectionView to Refresh. This in turn raises the Filter event that determines if each item in the list should still be there based on the text in the TextBox. Cool, eh? That’s all that’s needed

Run it with your favourite IDE with some suitable data, start typing and you have the basic concept of an autocompleting TextBox. That was easy.

Next time: we package this up in a reusable way.

Goal Shorts

A while back, I posted on the 4 things essential to successful dieting. I thought I’d expand a little on goal setting.

Last time, I said that you shouldn’t be using scale weight as your goal. It’s a fickle number and it’s a poor indicator of progress. Your body is made of up of, well, lots of stuff, but broadly it’s made of muscle, organs & bone, fat and water. Organ weight is something you can’t really manipulate. You can change the amounts of the other three; but here’s the kicker, though: muscle, which you want to maximize, weighs more than fat. This means that someone at 10% body fat at 200lbs is going to look better than someone at the same weight with 20% body fat. Suppose the guy at 20% bodyfat lost 20 pounds but stayed at 20%, so that he lost about the same amount of muscle as fat: Would he look better and hence feel better?

The final factor is water. Water weight is ephemeral but it’s very real if you happen to have a lot of it at weigh-in time. Say your goal for the week was 1.5 pound loss. But you ate just the right (or wrong) mix of carbs and fat that causes water retention so you actually post a gain for the week! It can be incredibly deflating when you worked so hard all week just to post a gain because of a poorly timed meal.

There’s got to be something better to measure.

We just had a burst of abnormally warm (for the time of year) weather in Ottawa, that required whipping out the summer clothing. I’ve been losing weight since October, so I haven’t worn my summer shorts or shirts since at least then, maybe even earlier. Nothing fit! It was all too big. Some of it just hangs there precariously on my hips waiting for a jaunty trip down the stairs to fall off and trip me up. Others require just a small tug downwards to do the same. My shirts, likewise don’t show off my gut anymore, cause I have a much smaller gut πŸ™‚

What an unexpected motivation!

One of the toughest things about physique transformation is you can’t get away from yourself. Because you’re always around yourself, you don’t really get to see the changes. So putting on a piece of clothing that you haven’t worn in a while can give you a real boost.

We were in Costco two weekends ago, probably buying big hunks of meat, when I came across a mountain of shorts at $16.99. Since none of my shorts fit quite right, I thought why not get a pair of shorts at a smaller size? If I didn’t fit into them right away, I’d work on getting into them. They’d be my goal shorts. So I bought them (the fiancee bought a pair of goal capri pants – which doesn’t have quite the same ring to it), took them home and tried them on.

They fit! Well, kinda: they fit at the waist a little snugly, so my muffin top got bigger, but I could sit in them comfortably. I try them on again this weekend. I shan’t disclose actual sizes for my fiancee, but she did better than I

Getting into some skinny pants or goal shorts is a great goal. It’s specific, measurable, and it’s clear if you succeeded.

Other good ways of measuring progress that don’t involve the scale are pictures and tape measurements. You may not see it in the mirror, or see it on the scale, but you will see it in the tape. Pictures are good to compare from time to time, especially in places that you don’t look at in the mirror, like in the neck and face. Make sure you take pictures with same clothes in the same spot in the same poses every time to compare properly.

If you are going to use scale weight as your main goal, I strongly suggest you use the other methods mentioned above in tandem. Here are some tips on making sure you’re using the scale effectively:

  • weigh yourself officially once a week; I say officially because I can’t help but weigh myself at other times, but I don’t change what I’m doing based on those unofficial measurements.
  • weigh yourself at the same time under the same circumstances. The time and circumstances I hear about the most, and the one I use is: in the morning, after peeing, totally naked.
  • Keep in mind what you did that week if the number isn’t what you were expecting. Last week I had a little too many carbs, which caused me to gain water weight. This masked any progress I made at the time that I weighed in. But the progress was there, so I didn’t fret or do anything drastic this week (just watched my carb intake a little better). I should post a good number this week.

Edit: The picture below isn’t me. It’s just an example of a good use of before/during photos. If you’re going to use photos as a measure of progress, take one of your front, side and back. Don’t flex, don’t suck in, don’t pose. The photo below is from the Physique Clinic at T-Nation. This guy lost 60 lbs in less than six months, most or all of it was fat, not muscle. You should check it out; it’s pretty inspiring.

Bartl's transformation on the T-Nation Physique Clinic: 60 lbs in under 6 months

It’s in the Framework, Dummy!

No one who knows me would describe me as humble. I guess if everyone thinks I’m not humble, maybe I’m not, I don’t know.

One thing I do approach with humility is my ability as a programmer. It took some concentration to “get” the fancy algorithms in university; I’d always try to solve the problem with brute force and “move up” as needed. I still do. I don’t think that’s wrong, either; worse is better. I practice TDD when I’m writing something that matters. I also remind myself that the first question isn’t “How do I do this?”, but “How has everyone done this before?”

Judging by the code I’ve read from my colleagues and online, a lot of people don’t share this perspective. They blindly assume that they have to solve every programming problem that crops up and that they can solve every problem better than everyone else who programmed before them ever. I doubt most programmers think that way but the results in the code could support that notion.

There are lots and lots of developers out there, all with a lot of the same types of problems to solve; some times – I’d say rarely – you need to revisit the problem yourself, but chances are, you can just use what other people have done. You can see this trend with the technologies and languages in use today verses, say 50 years ago. There’s a definite progression from machine code, to assembly, to procedural, to OO, to runtimes and frameworks. The code in J2EE or .NET or Python or Rails embodies thousands of little problems already solved for you.

To be a good programmer, therefore, one must get pretty good at searching the docs of your particular framework; learn to read source code; and always remember that someone already solved your problem. Even Isaac Newton didn’t do it alone. Being a humble programmer allows you to progress passed solved problems.

Before I end this post, a few examples from .NET:

  • File paths are something everyone has to deal with if you’re writing a desktop app. You have a directory path and a file name and you need to concatenate the two to work with the file on disk. You could write

    string path = dirPath + fileName;

    but that assumes that dirPath ends with ‘\’ on Windows (let’s not consider Mono right now). So, now we have to check to see if dirPath ends with ‘\’. Or, you could just use Path.Combine! It’s been in the framework since 1.0! That Path class has all kinds of good stuff on it. Use it! Stop reinventing the wheel.

  • Here’s one that I didn’t know about until a few weeks ago: Title case for a string involves capitalizing the first letter in every word. I’ll admit I’ve written functions in production scenarios, but I didn’t have to, and now I never will again because of the TextInfo.ToTitleCase method. TextInfo hangs off of CultureInfo, and it’s in the System.Globalization. I bet your naive implementation wouldn’t have considered internationalization. Microsoft has to deal with that a lot, they’re probably really good at it. Solve your problem, not one that Microsoft already has; it’s in the framework!

Here’s a rule I usually follow: if there is a requirement to do something, always, always, always, check the Google, or your favourite search engine to see what others have done.

Have you got any methods or classes that are in the framework but nobody uses?

The Missing .NET #2: Collection<T> AddRange()

The .NET framework is huge, but not so huge that it does everything for everyone; there are things that they in Redmond miss or don’t do for whatever reason but is still generally applicable to many developers. So, dear reader, I present to you a new series of posts on stuff I find missing in .NET, typically where even the Google fails to find the answer. It could be a useful class, a technique, a good practice or documentation that should be in the framework but isn’t.


One of the sad, unfortunate truths about Windows Forms development is that you don’t get to use it. That’s right: LINQ, WCF, WPF, maybe even generics, iterators, and the awesomest Winforms control ever, ToolStrip. All of it may be off limits to you, dear WinForms developer, because real people don’t know what the .NET framework is, and don’t care that your app depends on it; nor are they willing to sit through a 24 MB download, apparently. That last one seems really weird to me, a broadband user for 8 years, but, the numbers don’t lie: your users don’t have the framework on their computers. Now, there is hope with Vista β€” if Microsoft could just advertise it better so everyone’s perception of it isn’t that it sucks balls; it has .NET 3.0 installed by default, but .NET 3.5? Still a separate download.

That never-ending march forward of the .NET framework was a little disheartening to me: I felt the pressure to constantly stay on top of new stuff (and, oh, man is there ever a lot of new stuff since .NET 2.0: WPF, WCF, Workflow, LINQ, C# 3.0, not to mention all libraries the fast-moving ASP.NET team is pumping out), but there was a huge disconnect when I’d have to toil daily in the doldrums of .NET 1.1. So I unplugged, stopped blogging, just gave up on keeping up. “What was the point?” I’d ask.

I don’t really know what has spurred me on lately, but now I’m starting to get that passion back. So, I’ve been looking into some of the new stuff. Rather than jump right in with LINQ, I figured I’d start with some of the language improvements in C# 3.0, and in this post I’m going to go through an example of one of the easiest to grok, and one of the more powerful ones: extension methods.

One of the greatest classes in .NET 2.0 is List<T>. It is seriously awesome and, I assume, quite popular. What makes it so useful isn’t its strongly-typed nature, but the methods it exposes to access the strongly-typed collection, like Find(Predicate<T> match) and Foreach(Action<T> action). We’ve all written methods like this for arrays and ArrayList:

MyType Find(List<MyType> list)
{
    foreach (MyType t in list)
    {
        if (t.MyInt == 42)
            return t;
    }
    return null;
}

to find an element in the list. Or, something like this to perform an operation on every element in the list:

void Find(List<MyType> list)
{
    foreach (MyType t in list)
    {
        DoSomething(t);
    }
}

They’re both standard .NET 1.1 idioms. They clutter your code, it’s boilerplate, but you didn’t really have a choice. With List<T>, you can do these operations more succinctly:

MyType myType = list.Find(delegate(MyType t) { return t.MyInt == 42; });

and

list.ForEach(delegate(MyType t) { DoSomething(t); };

Beautiful!

So, why don’t we see List<T> being used everywhere? Well, the framework design guidelines say you shouldn’t publicly expose List<T>, that you should use Collection<T> instead. Krzysztof Cwalina, co-author of the excellent .NET Framework Design Guidelines, says why here. He has a point: you don’t want to expose methods unnecessarily, but those two above (Find(Predicate) and ForEach(Action) and let’s not forget AddRange()) are so useful. And it’s not unreasonable to want to find an element in a Collection<T> or do something to each element in the collection.

To do this is in the old-fashioned .NET 2.0 days, every time you wanted these methods, you’d have to create a custom collection and implement the method: Yuck. We’re also assuming that you control the collection class; perhaps you’re using a third-party component that exposes a Collection<T>, in which case, you’ll probably have to revert back to the .NET 1.1 idiom.

Now, in the latest and greatest .NET 3.5, you can write those methods once and use them wherever Collection<T> is exposed with extension methods! These things are a great way to add functionality that got missed to classes you don’t own. Consider this convoluted way of printing “Hello world”:

static void Main(string[] args)
{
    MyType[] array = {
                       new MyType{MyString="Hello", MyInt=42},
                       new MyType{MyString="World", MyInt=84},
                       new MyType{MyString="Jason", MyInt=92}
                     };

    List<MyType> list = new List<MyType>();
    list.AddRange(array);

    MyType myType = list.Find(delegate(MyType t) { return t.MyInt == 42; });

    Console.Write(myType.MyString);

    Console.Write(", ");

    Collection<MyType> collection = new Collection<MyType>();
    collection.AddRange(array);

    myType = collection.Find(delegate(MyType t) { return t.MyInt == 84; });
    Console.WriteLine(myType.MyString);
    Console.ReadLine();
}

class MyType
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
}

Note the collection class to print the world half. It’s got the AddRange() and the Find() method that List<T> does, which isn’t in its API. Those are extension methods.

The code that enables that is thus:

public static void AddRange<T>(this Collection<T> collection, IEnumerable<T> values)
{
    foreach (var item in values)
    {
        collection.Add(item);
    }
}

public static T Find<T>(this Collection<T> collection, Predicate<T> predicate)
{
    foreach (var item in collection)
    {
        if (predicate(item))
            return item;
    }
    return default(T);
}

The magic happens with the ‘this’ keyword in the method signature. Extension methods are truly cool: very powerful, and with great power, comes great responsibility. You should use it wisely.

Download the extension methods for Collection<T> here.