Reputation: 2956
I have two UserControls
One has a TreeView
and another has a Button
and a DataGrid
.
What i am trying to achieve is when Tab
on a TreeViewItem
should give KeyBoard Focus to the DataGrid in second UserControl.
I have looked in to different posts but no luck. find my XAML below,
<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>
simplified XAML for the question.
I have tried to set the focus to the Second UserControl
by adding event PreviewKeyDown
private void ExplorerView_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Tab)
{
Keyboard.Focus(TOCView);
}
}
But this give focus to the USerControl not to the DataGrid as i mentioned above.
Tried to Attach
a Property
to the DataGrid
. it worked as expected but not giving focus to the first row
. this thread given the input for that.
Solved :)
Created the AttachedProperty
mentioned in the thread above and modified the callback method to set the focus to the DataGrids
First Row like below,
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);
}
Please feel free to add any better solution. Thanks in Advance.
Upvotes: 1
Views: 1789
Reputation: 2956
Created the AttachedProperty
mentioned in the thread above and modified the callback method to set the focus to the DataGrids
First Row like below,
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);
}
Upvotes: 3