wpf RowDetailsTemplate 焦点

sea*_*nzi 5 wpf datagrid

我目前有一个带有 rowdetailstemplate 的数据网格,其中包含另一个数据网格以显示父子关系。第二个网格有一个列,其中包含一个按钮,单击该按钮会显示另一个对话框。

第一次显示行的详细信息时,用户必须在子网格中单击一次以获得焦点/激活它,然后再次单击以触发按钮单击事件。这仅在第一次显示一行时发生。

就像第一次点击被网格吞噬一样。我尝试捕获 RowDetailsVisibilityChanged 事件以尝试聚焦按钮,但它似乎仍然没有解决问题。

有任何想法吗?

Sam*_*uel 6

我会回答我自己的评论,它也可能对其他人有所帮助。以下 MSDN 条目解释并解决了该问题:http : //social.msdn.microsoft.com/Forums/vstudio/en-US/2cde5655-4b8d-4a12-8365-bb0e4a93546f/activation-input-controls-inside-datagrids- rowdetailstemplate-with-single-click?forum=wpf

问题是始终显示的行详细信息需要首先获得焦点。为了避免这个问题,需要一个 datagrid 预览处理程序:

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}"  BasedOn="{StaticResource {x:Type DataGridRow}}">
        <EventSetter Event="PreviewMouseLeftButtonDown" Handler="SelectRowDetails"/>
    </Style>
</DataGrid.RowStyle>
Run Code Online (Sandbox Code Playgroud)

注意:我已经扩展了它,因为它破坏了我的自定义 DataGridRow 样式以继承当前使用的样式。

处理程序本身是

private void SelectRowDetails(object sender, MouseButtonEventArgs e)
{
    var row = sender as DataGridRow;
    if (row == null)
    {
        return;
    }
    row.Focusable = true;
    row.Focus();

    var focusDirection = FocusNavigationDirection.Next;
    var request = new TraversalRequest(focusDirection);
    var elementWithFocus = Keyboard.FocusedElement as UIElement;
    if (elementWithFocus != null)
    {
        elementWithFocus.MoveFocus(request);
    }
}
Run Code Online (Sandbox Code Playgroud)

它将焦点设置在行详细信息的内容上,从而解决了单击两次的问题。

注意:这一切都取自 MSDN 线程,它不是我自己的解决方案。