MoveFocus不会在TabItem标头单击事件上触发

时间:2018-10-18 11:39:01

标签: c# .net wpf tabcontrol

DataGrid位于Tab1上。如果我位于Tab2上,然后单击Tab1标头,程序将切换到Tab1,并且DataGrid会滚动到正确位置的视图中,但是所选的{{ 1}}不会变得聚焦(突出显示),除非我再次单击Row标头。其余代码都可以正常触发。

CS

Tab1

XAML

private void Tab1_Clicked(object sender, MouseButtonEventArgs e)
{
    if (dg_address.SelectedIndex > -1)
    {
        dg_address.ScrollIntoView(dg_address.Items[dg_address.SelectedIndex]);
        DataGridRow row = (DataGridRow)dg_address.ItemContainerGenerator.ContainerFromIndex(dg_address.SelectedIndex);
        row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}

1 个答案:

答案 0 :(得分:1)

在这里找到了解决方案:https://social.msdn.microsoft.com/Forums/vstudio/en-US/3baa240a-c687-449e-af77-989ff4d78333/how-to-move-focus-to-a-textbox-in-a-tabcontrol-on-a-button-click?forum=wpf

private void Tab1_Clicked(object sender, MouseButtonEventArgs e)
{
    if (dg_address.SelectedIndex > -1)
    {
        dg_address.ScrollIntoView(dg_address.Items[dg_address.SelectedIndex]);
        Dispatcher.InvokeAsync(() =>
        {
            DataGridRow row = (DataGridRow)dg_address.ItemContainerGenerator.ContainerFromIndex(dg_address.SelectedIndex);
            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
        );
    }
}

private void Tab1_Clicked(object sender, MouseButtonEventArgs e)
{
    if (dg_address.SelectedIndex > -1)
    {
        dg_address.ScrollIntoView(dg_address.Items[dg_address.SelectedIndex]);
        Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
        {
            DataGridRow row = (DataGridRow)dg_address.ItemContainerGenerator.ContainerFromIndex(dg_address.SelectedIndex);
            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
        ));
    }
}

编辑:优化并删除了代码中的错误。