【问题标题】:MoveFocus won't trigger on TabItem Header click eventMoveFocus 不会在 TabItem 标题单击事件上触发
【发布时间】:2019-03-23 05:02:05
【问题描述】:

DataGrid 位于Tab1。如果我位于Tab2 并单击Tab1 标题,程序将切换到Tab1 并且DataGrid 滚动到正确位置的视图中,但选定的Row 不会获得焦点(突出显示) 除非我再次单击 Tab1 标题。其余代码触发就好了。

CS

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));
    }
}

XAML

<TabControl x:Name="tab_control"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            Background="#FFE5E5E5">

    <TabItem>
        <TabItem.Header>
            <Label Content="Seznam"
                   MouseLeftButtonDown="Tab1_Clicked"/>
        </TabItem.Header>

【问题讨论】:

  • 尝试使用Dispatcher.InvokeAsync(() =&gt; ... ) 执行您的代码以设置具有各种优先级的焦点(通常您需要Render 以确保WPF 完成渲染所需的一切)。由于 wpf 的某些延迟(排队)性质,这是此类情况下的“第一步”解决方案。
  • @Sinatr 你愿意解释一下 Dispatcher.InvokeAsync(() => ... ) 和 Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => ... ) 之间的区别吗,我是 C# 的新手,这两种方法产生相同的结果。
  • @Sinatr 自己找到了答案:stackoverflow.com/questions/13412670/…

标签: c# .net wpf tabcontrol


【解决方案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));
        }
        ));
    }
}

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

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2012-01-19
    • 2019-12-16
    • 2020-02-20
    • 2014-07-31
    • 2013-12-12
    相关资源
    最近更新 更多