wondra
wondra

Reputation: 3573

WPF focus DataGrid during GotFocus event of another control problem

According to the asnwer to Event for when KeyboardNavigation.TabNavigation Cycle occurs, the go-to solution is to add invisible control as last TabIndex of a Detail focus scope, handling GotFocus() on this dummy element. As part of handling this 'event' I would like to move focus back to master grid MasterDG.Focus():

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="2*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <DataGrid Name="MasterDG" ItemsSource="{Binding Items}" FocusManager.IsFocusScope="True"/>
    <StackPanel Name="Detail" Grid.Row="1"  FocusManager.IsFocusScope="True">
        <TextBox/>
        <TextBox/>
        <TextBox/>
        <Control Name="DummyControl" 
                 GotFocus="DummyControl_GotFocus"/>
    </StackPanel>
</Grid>

Event handler

private void DummyControl_GotFocus(object sender, RoutedEventArgs e)
{
    Save(); //save when done editing last element of detail
    MasterDG.Focus();
}

However this causes not only MasterDG to be focused but also enter Edit mode on current cell and insert \t character overwriting any cell content. How can I fix the issue?
Note the actual contents of Detail are dynamically generated.

Upvotes: 0

Views: 490

Answers (1)

mm8
mm8

Reputation: 169190

An easy workaround would be to call Focus() in the next dispatcher cycle:

private void DummyControl_GotFocus(object sender, RoutedEventArgs e)
{
    Save(); //save when done editing last element of detail
    Dispatcher.BeginInvoke(new Action(() => MasterDG.Focus()));
}

Upvotes: 1

Related Questions