views:

182

answers:

1

Hi there

I have a few usercontrols loaded into a tabcontrol via MVVM in WPF.

Within the XAML for the usercontrol I am setting focus to a textbox using the FocusManager, however this appears to only work when the first instance of the usercontrol is created.

Just to test I added a loaded event handler to the usercontrol - this is only called on the first instance.

I'm using data templates for the user controls as follows:

    <DataTemplate DataType="{x:Type local:UserTypeViewModel}">
        <local:UserTypeView />
    </DataTemplate>

The textbox is focused as follows:

    FocusManager.FocusedElement="{Binding ElementName=txtName}"

Additionally I'm using a global event handler (for the textbox GotFocus event) which selects all the text using a dispatcher.

If anyone has any tips on how to achieve focus with every usercontrol I'd be very grateful.

Thanks, Ben.

A: 

Remember that a visual element can only receive focus, if: * It is visible (in a TabControl only one tabitem can be visible at a time * IsFocusable must be set to true (is default false for UserControls) * It has finished loading (as you write - do it in the Loaded event))

I think the first reason is why it only works for the first element.

As for how to achieve it for all controls - you can use a style with an EventSetter for the Loaded event. You need to make a style per type of control though to avoid having to set it for each control.

Goblin