Managing focus with DataTemplates

1,242 views
Skip to first unread message

Mark Smith

unread,
Aug 7, 2008, 9:58:13 AM8/7/08
to wpf-di...@googlegroups.com
I've hit this problem a couple of times now and it always seems unnecessarily hard.. how are others setting the initial focus to items that are generated through a DataTemplate?  Here's the issue -- I have an application that dynamically builds up a set of fields and uses an ItemsControl to display them.  The ItemsControl uses a template like:
 
<DataTemplate>
    <Label ...>
    <TextBox ....>
</DataTemplate>
 
and I'd like the initial focus to be placed into the first TextBox in the ItemsControl.  I can do it in code behind by grabbing the Item generator and locating the first TextBox and forcing focus there, but there's got to be a better way -- ideally a way to specify it in XAML directly.  I've worked hard to try to keep the UI and code separated and it seems anti-WPF to have to know it's being rendered in an ItemsControl.  I've tried FocusManager but it consistently ignores me -- I suspect because the template hasn't expanded yet.
 
I wonder if I could create a  "initial focus" attached behavior to solve this in a once-for-all style .. I might pursue that next..
 
Thanks for any ideas!
mark

Mark Smith

unread,
Aug 7, 2008, 8:03:19 PM8/7/08
to WPF Disciples
So, I ended up creating an attached behavior which would delegate
focus from the items control to a specified template part - it's
somewhat ugly code (because it has to walk the tree to find the proper
element) but at least it's a reusable solution for XAML and not
hardcoded. Now I can do this to set focus to the 1st TextBox in the
items control:

<Grid FocusManager.FocusedElement="{Binding items}">

<Grid.Resources>
<DataTemplate x:Key="FooItem" DataType="{x:Type me:Foo}">
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<Label>Enter Some Text</Label>
<TextBox x:Name="templateTextBox" MinWidth="100"
Text="{Binding Text}" />
</StackPanel>
</DataTemplate>
</Grid.Resources>

<ItemsControl x:Name="items"
me:FocusForwarder.FocusedTemplateItem="templateTextBox"
ItemTemplate="{StaticResource FooItem}"
ItemsSource="{StaticResource fooArray}" />

</Grid>

Josh Smith

unread,
Aug 8, 2008, 7:48:40 AM8/8/08
to wpf-di...@googlegroups.com
Any chance you'll blog about that, Mark?  I think this is something that should be published!  :)

Mark Smith

unread,
Aug 8, 2008, 11:35:57 PM8/8/08
to wpf-di...@googlegroups.com
Why - you read my mind!

I think I might write something a bit longer on focus management in general .. it's not as simple as it it seems with FocusManager, focus scopes, logical & keyboard focus..  I'll try to post something in the next couple of days .. thanks Josh!
Reply all
Reply to author
Forward
0 new messages