When your application has a control on it that derives from Selector and has no items on load nothing is selected, obviously. During run-time when the user is clicking around and adds items to the Selector-derived control, you would assume that the control would automatically select the first item because that only makes sense. However, your assumption and mine would be wrong; this is not the behavior at all. Instead the selector will still have no items selected. This means in order to get this “Auto-select first item” behavior, you have to do it yourself. I’ve came up with a simple solution to this problem using only XAML.
<Style x:Key="SelectorAutoSelectStyle"
TargetType="{x:Type Selector}">
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="SelectedItem"
Value="{x:Null}" />
<Condition Property="HasItems"
Value="True" />
</MultiTrigger.Conditions>
<Setter Property="SelectedIndex"
Value="0" />
</MultiTrigger>
</Style.Triggers>
</Style>
<Style BasedOn="{StaticResource SelectorAutoSelectStyle}"
TargetType="{x:Type ListBox}" />
<Style BasedOn="{StaticResource SelectorAutoSelectStyle}"
TargetType="{x:Type ListView}" />
<!-- UPDATE: this causes problems for TabControls... -->
<Style BasedOn="{StaticResource SelectorAutoSelectStyle}"
TargetType="{x:Type TabControl}" />
Unfortunately as you can see, it requires more then one style to make this happen for ListBox, ListView, and TabControl. This is because styles can not be inherited. So what I’ve done there is created a “base style” and then applied that base style on to all the selector-derived controls. This works for all instances of the controls because I never supplied a Key for the styles, only a TargetType. I also keep this bit of code in my App.xaml in the Application.Resources property. This way it will be the default for all selector-derived controls anywhere in my application. So there you have it, and if you find a better solution be sure to add a comment to this post.
UPDATE (07-17-2009):
For some reason this technique causes problems for TabControls… they will no longer display anything in their content panel. I’m trying to figure out and solve the problem. I’ll update this post when I’ve done so. For now don’t use this technique for TabControls and just delete lines 22-25 in the code above.