1
votes

I have a Silverlight app, with a dataGrid in it, I added a TextBox to each row of the DataGrid, on the sixth column, now what I'm trying to accomplish here is, once the user presses the down key, the selected row changes, once it does the focus should be set to the TextBox, so that the user can input data.

Added text box to xaml, like so:

<sdk:DataGridTemplateColumn Header="Confirmation code" Width="Auto">
    <sdk:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBox/>
        </DataTemplate>
    </sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>

And added this to the xaml.cs under the DataGrid_SelectionChanged event:

private void BookingsView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TextBox content = DataGrid.Columns[6].GetCellContent(DataGrid.SelectedItem) as TextBox;
if (content != null) 
  content.Focus();
}

P.S : additionally, if possible, please suggest me a way, by which I can disable row selection of DataGrid but still, have the focus set to the text box upon keydown navigation..

1

1 Answers

1
votes

To access items inside data template you can use generic VisualTreeHelper method

private void DataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        var grid = sender as DataGrid;
        var cell = grid.Columns[6].GetCellContent(grid.SelectedItem).Parent as DataGridCell ;

        var textbox = FindFirstElementInVisualTree<TextBox>(cell);

               if(textbox !=null)
                   {
                      textbox.Focus();
                   }


    }

    private T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
    {
        var count = VisualTreeHelper.GetChildrenCount(parentElement);
        if (count == 0)
            return null;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(parentElement, i);

            if (child != null && child is T)
            {
                return (T)child;
            }
            else
            {
                var result = FindFirstElementInVisualTree<T>(child);
                if (result != null)
                    return result;

            }
        }
        return null;
    }
}`