Friday, October 29, 2010

How to databind the index of the element in the backing collection

Here's a quick tip. It's a hack in MeTL, you'll have to fiddle to make it fit your circumstance.

Imagine you've got an ItemsControl. You've got an ItemTemplate which controls rendering, and somewhere in there you'd like to be able to show the index (or the position if you don't want to assume that your clients understand zero indexing) visually. What do you databind and how?

There's no inherent property, and the elements can't access their containing collection (for obvious reasons - they could be in 4000 different collections for all you know - it's a one way relationship).

MyStuff/ShowList.xaml


MyStuff/ShowList.xaml.cs


That's it. The reason I think it's a shitty hack is because you have to set your ElementIndexConverter up before you call InitializeComponent or terrible things happen. I think we've all got enough java reflexes left over that we tend to try to call the default stuff in lieu of the super constructor as the first statement, and might even automatically reorganize it. Furthermore, ValueConverters really feel to me like they should be very generic, and this one is locked down to its constructed collection. Still, it's handy to be able to do this when you need to.

2 comments:

  1. Well, shit. Do I have to write my own goddamn blog software to make code represent nicely? Damn.

    ReplyDelete
  2. Resorted to gists. Getting closer, anyway.

    ReplyDelete