Monday, June 30, 2008

WPF ListBoxItem Double Click

The WPF ListBox does not have an event which fires when an item in the list is double clicked. As far as I can tell, there is no simple mechanism to accomplish this.

The best solution I've found is using the ListBox.MouseDoubleClick event. This event fires every time the mouse is double clicked anywhere in the listbox. This includes the background (if your items don't completely fill your list) and the scroll bar.

What you have to do is use the ListBox.InputHitTest method to get the element in the ListBox's Visual Tree which was clicked. Then you have to loop up the VisualTree until you find either a ListBoxItem (which means an item was double clicked), or the ListBox (which means an item was not double clicked).

Here's the code where ctlList is the ListBox:
void ctlList_MouseDoubleClick( object sender, MouseButtonEventArgs e )
UIElement elem = (UIElement)ctlList.InputHitTest( e.GetPosition( ctlList ) );
while ( elem != ctlList )
if ( elem is ListBoxItem )
object selectedItem = ( (ListBoxItem)elem ).Content;
// Handle the double click here
elem = (UIElement)VisualTreeHelper.GetParent( elem );

I haven't been able to find another way to do this yet. There may be one flaw with this: If you use a DataTemplate in your list box, and a control in that template handles the MouseDoubleClick, I think it's possible the ListBox's event wont fire. Again, I haven't verified this, so it might work just fine.

If you know of a better way to get the double click on a list box item in WPF, please let me know!

UPDATE: Some commenters found a possible problem with the approach demonstrated in this post and offered an alternative method.

The problem is that it's possible the InputHitTest method could return something that is not a UIElement. This might happen if you had a Span element in your list box item template, for example.

The alternative method is to define a style for your list box's item container than includes an event hook for MouseDoubleClick.

<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseDoubleClick" Handler="listBoxItem_DoubleClick" />

Thanks to Steve and Mark for pointing this out!

Friday, June 27, 2008

IoC and DI complexity

Inversion of Control Containers (Ioc), Dependency Injection (DI), and the Dependency Inversion Principle (DIP) are huge blogosphere topics these days.

Quickly, Dependency Injection (DI) is a pattern of “injecting” a class’s “dependencies” into it at run time. This is done by defining the dependencies as interfaces, then passing in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. As a side effect, it also causes you to follow the Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks.

Dependency Inversion (DIP) is a design principle which is in some ways related to the Dependency Injection pattern. The idea here is that “high” layers of your application should not directly depend on “low” layers. Instead, the high layers should define interfaces for the behavior they expect (dependencies), and the low layers will come along and implement those interfaces. The benefit of following this principle is that the high layers become somewhat isolated form the low layers. This means if some arbitrary change is made in the low layer it is less likely to have to be propagated up through all the layers. Dependency Inversion does not imply Dependency Injection. This principle doesn’t say anything about how high layers know what low layer to use. This could be done by simply using the low layer directly in the code of the high layer, or through Dependency Injection.

The Inversion of Control Container (IoC) is a pattern that supports Dependency Injection. In this pattern you create a central container which defines what concrete classes should be used for what dependencies through out your application. Now, your DI classes will determine their dependencies by looking in the IoC container. This removes any specification of a default dependency from the classes themselves, and it makes it much easier to change what dependencies are used on the fly.

Clearly, these are some very powerful patterns and principles. Basically, DI and IoC remove the compile time definition of the relationships between classes and instead define those relationships at runtime. This is incredibly useful if you think you may need to modify the way your application behaves in different scenarios.

However, if you pay attention to why these patterns are primarily used by the various people talking about them in the blogosphere you’ll see that it’s for unit testing. The reason people are bothering is because they want to create mocks and stubs of their objects so that they can write unit tests. The Dependency Inversion and Single Responsibility principles that arise from this are certainly an added bonus, but not the primary goal. And the ability to swap in different REAL dependencies is not one that anyone planed to use.

Let’s be realistic. How many applications really need to be able to do the same thing in two different ways at the same time? That’s what DI is for, but I don’t think many people really need that capability. It’s much more likely that your application will evolve from doing THIS to doing THAT. DI will make this migration simpler, but only because it forced you into following SRP and DIP. You could have followed those principles without using DI.

The question is, “If your application doesn’t require DI (except for unit tests), should you use DI?”

The question that leads to is, “What's the harm in using DI for unit testing?”

The answer to that is: complexity. Using DI adds complexity to your application. IoC adds even more complexity.

Where does the complexity come from?
  • There are more pieces and components to keep track of
  • It’s harder for a person to understand how everything fits together into a functioning whole
  • There are more restrictions on the things you can do in your code: you can’t new up a dependency; you can’t require fields through a dependency’s constructor, etc
  • Interfaces can’t strictly define everything (will it throw an exception, will it return null, will it display it’s own error dialogs, etc)
  • With some IoC tools, I have to maintain an xml configuration file…
  • There are simply more lines of code
  • It is harder to browse the code and debug the code (because there are more layers and indirection)
When I brought this up in comments on the YTechie blog everyone told me the problem wasn’t with the patterns, it was with my IDE, or it was because I wasn’t commenting my interfaces well enough… This was mostly because the examples I was using to try to indicate the complexity were trivial.

The point I’m actually trying to make is just that there is more complexity! I need a better IDE because of it! I have to write more detailed implementation specific comments because of it! It doesn't really matter if doing those things are a good idea anyway. The point is that now it's complicated enough that I have to do them, I can't get by without like I could before.

To put it simply, I have to do more work. That’s the harm in DI and IoC (and to a lesser extent DIP): complexity -> more work -> more confusion -> more potential for error -> more chaos over time

The next question is, “Is this added complexity enough of a downside to make DI/IoC not worth it?”

This is the real question that everyone should ask themselves before they dive head first into the newest latest thing. Unfortunately, you’ll find a surprising lack of thought about this. Or even willingness to think about it. When people find something new they like, they don't like to admit it may come with some downsides too, however minor they may be. Don't get me wrong! Some people are thinking about it, like Dave^2. But it the blog world, it's always a struggle to get passed the "It's awesome" to the "but...".

The answer to our question is: It Depends. That’s the Computer Engineer’s motto. And it’s hugely important to remember that it always depends. It depends on your circumstances, and the complexity of your application or component, and an innumerable list of other factors. It's not an all or nothing answer either. It could be no problem here, and total disaster there.

Are having unit tests worth the added complexity for you? As long as you recognize the complexity, you’re fully qualified to make that decision. Personally, I've found many circumstances in which it was worth it, and a few others where it was just too much overhead. But let me know what you decide, and how it works out for you.

Monday, June 23, 2008

Custom Drop Downs

For at least the last year I have had an unhealthy obsession with drop downs. Custom drop downs really.

That is, combo boxes. But when you click on the down arrow, you get a list with check boxes. Or a tree control. Or a tree control with check boxes. Or a custom edit surface with a text box and an "Apply" button. Or anything you can possibly imagine, really.

All of these things are immensely useful. And if the story ended there I would never have become so obsessed. Sadly, the story continues. It turns out, such things are not exactly easy to build.

My first attempt involved Subclassing the .NET combo box. I got a working drop down in the end, but it had some odd behavior, and was overall just a huge hack.

Next I learned that Infragistics had a component that you could use to create custom drop downs. Put any control in it you want and you're off to the races. For a time, my obsession was sated. Until we learned that this component could not be resized after it was opened. To resize it, you had to close it and reopen it. This results in noticeable, seizure inducing, flickering. And that = bad.

Later, I learned about how easy this was to do with WPF. In fact, it was the very first thing I ever tried in WPF. But that doesn't help me much at work where our software is all WinForms.

Fortunately, this story has a happy ending! It turns out that .NET 2.0 introduced a component much like the Infragistics one but without the added suck!

It is called the ToolStripDropDown. Basically it's just a Form with special properties that make it behave like a popup. It doesn't steal focus when it opens. It closes as soon a user clicks off it. It can have a shadow border (if you'd like) like a context menu. You can override its default close behavior by using the Closing event and checking the e.CloseReason enumeration value and setting e.Cancel = true. And best of all, it can host any .NET control you want to put in it, as long as you host that control in a TreeStripControlHost.

I stumbled on it at jfo's blog here and immediately put it into use. In the process of trying to do some wacky custom stuff I found the same material from jfo's blog, but on msdn here which you might prefer. Both of those show example code for putting a treeview in a custom drop down.

I must have spent months working on this problem. I probably executed thousands of Google searches looking for solutions. All I ever came across was people using borderless forms and the deactivate event, which doesn't quite cut it for all cases. So when I finally discovered this, my obsession compelled me to post about it.

The only thing that I haven't tried yet is making a "suggest" combo box using this technique. This is a control in which when the user types, you execute a stored procedure and fill the drop down with matching items. The potential problem spot here is that you need focus on the text box so you can type, but you need the drop down to be open. I'm guessing you could pull this off with the ToolStripDropDown though. If anyone knows for sure, please leave a comment!

Monday, June 16, 2008

Fun with Casting

This is a .NET specific post. I ran into this interesting behavior the other day. It makes perfect sense, but I'd never thought about it before so I thought I'd share.

object o = 5.0;
int i = (int)o;

That code will bomb out with a run time exception complaining about an invalid cast.

object o = 5.0;
int i = (int)(double)o;

That code will run just fine.

What's happening is the meaning of the cast is different. In the first case I'm saying that I expected there to be an int in the object. There isn't, it's a double. So it blows up. In the second case I'm saying that I expected there to be a double in the object and that I want it to truncate the double into an int. It's slightly unexpected because the same syntax means two different things depending on the types it's acting on.

Monday, June 9, 2008

Powershell Grep

If you're into Powershell, you may wish you could issue a grep command like you can in Linux. Guess what? You can!  Grep is a command that can search the contents of files for a regular expression.

In Powershell, we can do the same like so:
dir | select-string "my regex"

This command returns any matches (line by line) in any files in the current directory.  And if you want it to search through subdirectories as well:
dir -recurse | select-string "my regex"

If you have anything other than text files, this will dump a lot of nonsense and do a lot of really annoying beeping. To fix that you can tell it to only search files of a certain extension:
dir -recurse -include *.txt,*.cs | select-string "my regex"

This works great, but it's a lot of have to type, so I define a function in my $profile which I named grep.  You can check out my posh-prefs profile on bitbucket.

If all you wanted was to look at the names of the files, instead of the contents, you could:
dir | where { $_ -match "prefix*" }

Okay, I was just messing with you. You'd ACTUALLY do it like:
dir prefix*

Or recursively:
dir -recurse -include prefix*

Not only is this way shorter, it's actually more efficient because "the provider applies [it] when retrieving the objects, rather than having Windows PowerShell filter the objects after they are retrieved" (according to help dir -detailed).

Monday, June 2, 2008

State of the Blog

I've been writing this blog for 1 year and 1 month. In that time I have put up 64 posts, that's 4.9 posts per month on average. I've had 76 comments (including my own), that's 1.2 comments per post on average. Feedburner believes there are between 14 and 19 people who subscribe to this blog day to day. Google Analytics indicates that this blog gets anywhere from 8 (on weekends) to 52 Visits a day. The vast majority of those visits are brought in from Google searches.

I find these numbers interesting, but mostly irrelevant. I don't really care what those numbers look like. I'm primarily motived by these three objectives:
  1. To challenge myself to keep tackling new problems and learning new things and evaluating the things I have done
  2. To get in touch with people outside my little company who have different viewpoints and different experiences
  3. To keep an archive so I can lookup things I've figured out or thought about in the past or so I can refer other people to them
That said, its good to have goals and its good to evaluate what you're doing (which is the point of this blog after all). Even though this is cheesy and goes against what I usually try to do here, I thought it might be worth a shot: So I want to solicit some feedback and ask a few questions.

I have one person who posts here regularly (thanks Josh!). Frequently he just says "duh" or "I've seen it slightly different" but I love that. It tells me other people have been through it. I'm not looking for expert comments, after all, I'm no expert. But I would really love to hear more of what people think, even if its just a gut reaction.
1. What can I do to draw more comments?

I write about things I'm interested in or working on. That's why the topics range so widely and randomly. I also try to write when I'm confident that I've come to a resolution. That's why what I write is less like a blog and more like little essays or articles. I also write as if what I'm saying is true, even when I know I could be wrong or when I haven't had a chance to exercise the ideas much. I find second guessing and apologizing in writing to be really irritating and I assume you'll do the second guessing on your own as you read.
2. Should I change anything about the topics or style?

I write when I have something to say. I shoot for 4 posts a month (but not necessarily one a week). Other than that I don't keep a schedule. I do this because I don't want to publish half formed thoughts or minor mostly content-less topics. But I've read lots of people who say you should post on a regular schedule.
3. Should I adopt a schedule?

I write this stuff for fun mainly. But it would be more fun if it was less one sided.
4. Do you have any feedback, or is it all perfect just the way it is?