Skip to content

Commit

Permalink
Focusing on new row when pressing add expense
Browse files Browse the repository at this point in the history
  • Loading branch information
arpitmathur committed Feb 11, 2020
1 parent a3a320b commit 4a2a659
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;

namespace ExpenseItDemo
{
Expand All @@ -15,11 +21,55 @@ public CreateExpenseReportDialogBox()
InitializeComponent();
}


private void addExpenseButton_Click(object sender, RoutedEventArgs e)
{
var app = Application.Current;
var expenseReport = (ExpenseReport) app.FindResource("ExpenseData");
expenseReport?.LineItems.Add(new LineItem());
DataGridRow row =null;
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, new Action(() =>
{
row = expenseDataGrid1.ItemContainerGenerator.ContainerFromIndex(expenseDataGrid1.Items.Count - 1) as DataGridRow;
if (row != null)
{
expenseDataGrid1.SelectedItem = row.DataContext;
DataGridCell cell = GetCell(expenseDataGrid1, row, 0);
if (cell != null)
{
expenseDataGrid1.CurrentCell = new DataGridCellInfo(cell);
Keyboard.Focus(cell);
}
}
}));
}
private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
{
if (rowContainer != null)
{
DataGridCellsPresenter presenter = RecursiveVisualChildFinder(rowContainer);
if (presenter != null)
return presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
}
return null;
}

private static DataGridCellsPresenter RecursiveVisualChildFinder(DependencyObject myObj)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myObj); i++)
{
// Retrieve child visual at specified index value.
DependencyObject childObj = VisualTreeHelper.GetChild(myObj, i);

// Do processing of the child visual object.
if(childObj is DataGridCellsPresenter)
{
return (DataGridCellsPresenter)childObj;
}
// Enumerate children of the child visual object.
return RecursiveVisualChildFinder(childObj);
}
return null;
}

private void viewChartButton_Click(object sender, RoutedEventArgs e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@
ItemsSource="{Binding LineItems}"
HeadersVisibility="Column"
Name="expenseDataGrid1"
AutoGenerateColumns="False">
AutoGenerateColumns="False"
CanUserAddRows="False">
<DataGrid.ToolTip>
<TextBlock>Expense Report</TextBlock>
</DataGrid.ToolTip>
Expand Down

0 comments on commit 4a2a659

Please sign in to comment.