键盘焦点wpf:当从不同的UserControls树视图按TAB键时,将键盘焦点设置为datagrid的第一行
本文关键字:键盘 焦点 datagrid 设置 一行 wpf TAB 视图 UserControls 键时 | 更新日期: 2023-09-27 18:14:50
我有两个UserControls
一个有TreeView
,另一个有Button
和DataGrid
。
我想要实现的是当Tab
上的TreeViewItem
应该在第二个UserControl中给予键盘焦点到DataGrid。
我看过不同的帖子,但没有运气。找到我的XAML下面,
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<UC:ExplorerView DataContext="{Binding ExplorerViewModel}" Grid.Row="0"/>
<UCs:TableOfContentView DataContext="{Binding TableOfContentViewModel}" x:Name="TOCView" Grid.Row="1"/>
</Grid>
简化了问题的XAML。
我试图通过添加事件PreviewKeyDown
将焦点设置为第二个UserControl
private void ExplorerView_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Tab)
{
Keyboard.Focus(TOCView);
}
}
但是这将焦点放在USerControl上,而不是上面提到的DataGrid上。
试图将Attach
从Property
转到DataGrid
。它像预期的那样工作,但没有关注first row
。这个线程给出了输入。
:
)创建上面线程中提到的AttachedProperty
,并修改回调方法,将焦点设置为DataGrids
第一行,如下所示,
private static object OnCoerceValue(DependencyObject d, object baseValue)
{
if (((DataGrid)d).HasItems)
{
DataGridRow row = ((DataGrid)d).ItemContainerGenerator.ContainerFromIndex(0) as DataGridRow;
if(row !=null)
{
if ((bool)baseValue)
{
FocusManager.SetIsFocusScope(row, true);
FocusManager.SetFocusedElement(row, row);
}
else if (((UIElement)d).IsFocused)
Keyboard.ClearFocus();
}
}
return ((bool)baseValue);
}
请随意添加任何更好的解决方案。
创建上面线程中提到的AttachedProperty
,并修改回调方法,将焦点设置为DataGrids
第一行,如下所示,
private static object OnCoerceValue(DependencyObject d, object baseValue)
{
if (((DataGrid)d).HasItems)
{
DataGridRow row = ((DataGrid)d).ItemContainerGenerator.ContainerFromIndex(0) as DataGridRow;
if(row !=null)
{
if ((bool)baseValue)
{
FocusManager.SetIsFocusScope(row, true);
FocusManager.SetFocusedElement(row, row);
}
else if (((UIElement)d).IsFocused)
Keyboard.ClearFocus();
}
}
return ((bool)baseValue);
}