#region Using
using Autofac;
using BatoirApp.Model;
using BatoirApp.MVVM.Services;
using BatoirApp.View;
using BatoirApp.View.Orders;
using BatoirApp.View.Payments;
using BatoirApp.View.UserControls;
using BatoirApp.ViewModel;
using BatoirApp.ViewModel.Orders;
using BatoirApp.ViewModel.Payments;
using BatoirApp.ViewModel.Products;
using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
#endregion
namespace BatoirApp.MVVM.Behaviors
{
public class KeyTriggerBehaviorNew : Behavior
{
#region Services
private INavigationService _navigationService;
#endregion
#region Datagrid fields
private OrderProductLine datagridCurrentItem;
private bool IsColumnsEnabled;
private int _lastKnownColumnIndex = 0;
private int _previousColumnIndexThatHandleUpKey;
private bool isEditingInProgress = false;
private TextBox _cachedProductNameCellText;
private AutoCompleteTextBox.Editors.AutoCompleteComboBox _cachedProductNameCell;
private DataGrid datagrid;
private AutoCompleteTextBox.Editors.AutoCompleteComboBox ProductNameCell;
private TextBox ProductNameCellText;
private HashSet<object> addedRows = new HashSet<object>();
private Dictionary<object, bool> addedRowsWithCancelFlag = new Dictionary<object, bool>();
private ObservableCollection<OrderProductLine> orderProductLines;
#endregion
#region NewOrderUserControl fields
private bool _notesJustOpened = false;
private NewOrderUserControlViewModel viewModel;
private NewOrderUserControl newOrderUserControl;
private bool CanShowOrderNote;
#endregion
#region ??????
private object _originalKeySource;
private bool IsUiThread;
#endregion
#region OnAttached & OnDetaching
#region OnAttached
protected override void OnAttached()
{
base.OnAttached();
#region Services
_navigationService = App.Container.Resolve<INavigationService>();
#endregion
#region Check associatedObject type
if (AssociatedObject is FrameworkElement frameworkElement)
{
#region If NewOrderUserControl
if (AssociatedObject is NewOrderUserControl)
{
frameworkElement.Loaded += OnNewOrderControlLoaded;
}
#endregion
#region If MainWindowView
else if (AssociatedObject is MainWindowView)
{
frameworkElement.Loaded += MainWindowLoaded;
}
#endregion
}
#endregion
}
#endregion
#region OnDetaching
protected override void OnDetaching()
{
base.OnDetaching();
if (AssociatedObject is FrameworkElement frameworkElement)
{
;
// Subscribe to the Loaded event if it's a FrameworkElement
frameworkElement.Loaded -= OnNewOrderControlLoaded;
}
}
#endregion
#endregion
#region MianWindow
#region Methods
private void MainWindowLoaded(object sender, RoutedEventArgs e)
{
var mainWindow = sender as MainWindowView;
mainWindow.PreviewKeyDown += MainWindow_PreviewKeyDown;
var topMenu = mainWindow.topMenu;
var sellMenuItem = topMenu.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "SellMenuItem");
var dataMenuItem = topMenu.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "DataMenuItem");
sellMenuItem.Click += SellMenuItem_Click;
dataMenuItem.Click += DataMenuItem_Click;
}
private void OrdersMenuItem_Click(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
var mainWindow = sender as MainWindowView;
if (e.Key == Key.Escape)
{
// Get the original source of the key press
DependencyObject source = e.OriginalSource as DependencyObject;
var contentControl = FindChild<ContentControl>(Application.Current.MainWindow, "userControlContent");
if (IsChildOf(contentControl, source))
{
if (contentControl.Content is BatoirApp.ViewModel.Orders.NewOrderUserControlViewModel)
{
e.Handled = false;
return;
}
else if (contentControl.Content is BatoirApp.ViewModel.Orders.OrdersViewModel)
{
e.Handled = false;
return;
}
}
// Handle the ESC key for other cases
var topMenu = FindChild<Menu>(mainWindow, "topMenu");
var fileMenuItem = FindChild<MenuItem>(topMenu, "FileMenuItem");
if (topMenu != null)
{
bool isAnyMenuOpen = false;
foreach (MenuItem item in topMenu.Items)
{
if (item.IsSubmenuOpen)
{
isAnyMenuOpen = true;
item.IsSubmenuOpen = false;
}
}
if (!isAnyMenuOpen && fileMenuItem != null)
{
if (fileMenuItem.IsFocused)
{
var r = new ExitAppMessageBox();
r.ShowDialog();
}
else fileMenuItem.Focus();
}
e.Handled = true;
}
}
}
#endregion
#region Menu
#region Methods
private void DataMenuItem_Click(object sender, RoutedEventArgs e)
{
var dataMenuItem = sender as MenuItem;
if (dataMenuItem != null)
{
foreach (var subMenuItem in dataMenuItem.Items.OfType<MenuItem>())
{
if (subMenuItem.Name == "ProductsSubMenuItem")
{
_navigationService.NavigateTo<ProductsListViewModel>();
var parentMenu = dataMenuItem.Parent as Menu;
var newOrderMenuItem = dataMenuItem.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "NewOrderMenuItem");
newOrderMenuItem?.Focus();
}
else if (subMenuItem.Name == "SubMenuItem2")
{
MessageBox.Show("SubMenuItem2 clicked");
}
}
}
}
private void SellMenuItem_Click(object sender, RoutedEventArgs e)
{
var sellMenuItem = sender as MenuItem;
if (sellMenuItem != null)
{
if (e.OriginalSource is MenuItem clickedItem)
{
switch (clickedItem.Name)
{
case "NewOrderMenuItem":
var parentMenu = sellMenuItem.Parent as Menu;
var newOrderMenuItem = sellMenuItem.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "NewOrderMenuItem");
newOrderMenuItem?.Focus();
App.Current.Dispatcher.BeginInvoke(new Action(() =>
{
_navigationService.NavigateTo<NewOrderUserControlViewModel>();
newOrderMenuItem?.Focus();
}), System.Windows.Threading.DispatcherPriority.Input);
break;
case "OrdersMenuItem":
_navigationService.NavigateTo<OrdersViewModel>();
break;
// Add other cases if there are additional submenus under SellMenuItem
}
}
}
}
#endregion
#endregion
#endregion
#region NewOrderControl
#region Main newOrderControl
private void OnNewOrderControlLoaded(object sender, RoutedEventArgs e)
{
newOrderUserControl = sender as NewOrderUserControl;
viewModel = newOrderUserControl.DataContext as NewOrderUserControlViewModel;
datagrid = newOrderUserControl.itemsInNewOrderDatagrid;
if (datagrid != null)
{
datagrid.PreviewKeyDown += Datagrid_PreviewKeyDown;
datagrid.CellEditEnding += Datagrid_CellEditEnding;
datagrid.PreparingCellForEdit += Datagrid_PreparingCellForEdit;
datagrid.SelectedCellsChanged += Datagrid_SelectedCellsChanged;
}
newOrderUserControl.KeyDown += NewOrderUserControl_KeyDown;
newOrderUserControl.ClientTextBox.Focus();
newOrderUserControl.ClientTextBox.PreviewLostKeyboardFocus += ClientTextBox_PreviewLostKeyboardFocus;
newOrderUserControl.ClientTextBox.KeyDown += (sender, args) =>
{
if (args.Key == Key.Enter)
{
if (datagrid.Items.Count > 0)
{
if (datagrid.Items.Count > 0)
{
datagrid.Focus();
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[0], datagrid.Columns[_previousColumnIndexThatHandleUpKey]);
args.Handled = true;
//datagrid.ScrollIntoView(datagrid.Items[0], datagrid.Columns[0]);
}
}
else
{
if (viewModel.SelectedCustomer != null)
{
//var orderLines = datagrid.ItemsSource as ObservableCollection<OrderProductLine>;
//orderLines.Add(new OrderProductLine { });
orderProductLines = datagrid.ItemsSource as ObservableCollection<OrderProductLine>;
orderProductLines.Add(new OrderProductLine { });
datagrid.UpdateLayout();
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[0], datagrid.Columns[1]);
datagrid.Focus();
datagrid.BeginEdit();
ProductNameCell = FindChild<AutoCompleteTextBox.Editors.AutoCompleteComboBox>(datagrid, "ProductNameCell");
ProductNameCellText = FindChild<TextBox>(ProductNameCell, "PART_Editor");
_cachedProductNameCell = ProductNameCell;
_cachedProductNameCellText = ProductNameCellText;
ProductNameCellText.Focus();
}
}
}
else if (args.Key == Key.Escape)
{
if (datagrid.Items.Count > 0)
{
datagrid.Focus();
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[0], datagrid.Columns[_previousColumnIndexThatHandleUpKey]);
//datagrid.ScrollIntoView(datagrid.Items[0], datagrid.Columns[0]);
}
else
{
_navigationService.NavigateTo<MainWindowViewModel>();
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
var mainWindow = Application.Current.Windows.OfType<MainWindowView>().FirstOrDefault();
if (mainWindow != null)
{
var topMenu = mainWindow.topMenu;
var sellMenuItem = topMenu.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "SellMenuItem");
if (sellMenuItem != null)
{
var newOrderMenuItem = sellMenuItem.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "NewOrderMenuItem");
if (newOrderMenuItem != null)
{
mainWindow.Focus();
sellMenuItem.IsSubmenuOpen = true;
newOrderMenuItem.Focus();
}
}
}
}), System.Windows.Threading.DispatcherPriority.Input);
}
}
};
newOrderUserControl.DeleteConfirmationBox.ConfirmationResult += (s, confirmed) =>
{
var currentItem = datagridCurrentItem;
if (confirmed)
{
foreach (UIElement element in newOrderUserControl.MainGrid.Children) // Adjust MainGrid to your parent container
{
// Check if the element is not the DeleteConfirmationBox
if (element != newOrderUserControl.DeleteConfirmationBox)
{
element.IsEnabled = true;
}
}
if (currentItem != null)
{
orderProductLines.Remove(currentItem as OrderProductLine);
datagrid.SelectedCells.Clear();
var cellInfo = new DataGridCellInfo(datagrid.Items[0], datagrid.Columns[1]);
datagrid.SelectedCells.Add(cellInfo);
datagrid.Focus();
Keyboard.Focus(datagrid);
datagrid.CurrentCell = cellInfo;
}
// Reset row background if needed
var row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(currentItem);
if (row != null)
{
row.Background = new SolidColorBrush(System.Windows.Media.Colors.White);
}
}
else
{
foreach (UIElement element in newOrderUserControl.MainGrid.Children) // Adjust MainGrid to your parent container
{
// Check if the element is not the DeleteConfirmationBox
if (element != newOrderUserControl.DeleteConfirmationBox)
{
element.IsEnabled = true;
}
}
datagrid.SelectedCells.Clear();
var cellInfo = new DataGridCellInfo(datagrid.Items[0], datagrid.Columns[1]);
datagrid.SelectedCells.Add(cellInfo);
datagrid.Focus();
Keyboard.Focus(datagrid);
datagrid.CurrentCell = cellInfo;
var row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(currentItem);
if (row != null)
{
row.Background = new SolidColorBrush(System.Windows.Media.Colors.White);
}
}
};
}
private void NewOrderUserControl_KeyDown(object sender, KeyEventArgs e)
{
if ((Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.N))
{
if (CanShowOrderNote)
{
if (datagrid.Items.Count > 0)
{
if (newOrderUserControl.NotesSection.Visibility == Visibility.Collapsed)
{
_originalKeySource = e.OriginalSource;
newOrderUserControl.NotesSection.Visibility = Visibility.Visible;
newOrderUserControl.OrderNotesTextBox.Focus();
newOrderUserControl.ClientTextBoxGrid.IsEnabled = false;
newOrderUserControl.OrderTotalStackPanel.IsEnabled = false;
newOrderUserControl.itemsInNewOrderDatagrid.IsEnabled = false;
}
else if (newOrderUserControl.NotesSection.Visibility == Visibility.Visible)
{
newOrderUserControl.NotesSection.Visibility = Visibility.Collapsed;
newOrderUserControl.ClientTextBoxGrid.IsEnabled = true;
newOrderUserControl.OrderTotalStackPanel.IsEnabled = true;
newOrderUserControl.itemsInNewOrderDatagrid.IsEnabled = true;
if (IsChildOf(newOrderUserControl, _originalKeySource as DependencyObject))
{
(_originalKeySource as UIElement)?.Focus();
}
}
}
else return;
}
}
else if (e.SystemKey == Key.F10)
{
if (datagrid.Items.Count >= 1)
{
// Show confirmation dialog
MessageBoxResult result = MessageBox.Show(
"Are you sure you want to cancel the order?",
"Cancel Order Confirmation",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
// Check the result and act accordingly
if (result == MessageBoxResult.Yes)
{
_navigationService.NavigateTo<MainWindowViewModel>();
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
var mainWindow = Application.Current.Windows.OfType<MainWindowView>().FirstOrDefault();
if (mainWindow != null)
{
var topMenu = mainWindow.topMenu;
var sellMenuItem = topMenu.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "SellMenuItem");
if (sellMenuItem != null)
{
var newOrderMenuItem = sellMenuItem.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == "NewOrderMenuItem");
if (newOrderMenuItem != null)
{
mainWindow.Focus();
sellMenuItem.Focus();
sellMenuItem.IsSubmenuOpen = true;
newOrderMenuItem.Focus();
}
}
}
}), System.Windows.Threading.DispatcherPriority.Input);
}
else
{
return;
}
}
}
}
private void ClientTextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var clientTextBox = sender as AutoCompleteTextBox.Editors.AutoCompleteComboBox;
var enteredClient = clientTextBox?.Text;
var newOrderControl = FindParent<NewOrderUserControl>(clientTextBox);
var viewModel = newOrderControl?.DataContext as NewOrderUserControlViewModel;
if (Keyboard.IsKeyDown(Key.Escape))
{
e.Handled = false;
return;
}
if (string.IsNullOrWhiteSpace(enteredClient) ||
viewModel.AvailableCustomers.FirstOrDefault(c => c.FirstName.Equals(enteredClient, StringComparison.InvariantCultureIgnoreCase)) == null)
{
e.Handled = true;
}
}
#endregion
#region Datagrid
private void Datagrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
if (datagrid.CurrentColumn != null)
{
_lastKnownColumnIndex = datagrid.Columns.IndexOf(datagrid.CurrentColumn);
}
}
private void Datagrid_PreparingCellForEdit(object? sender, DataGridPreparingCellForEditEventArgs e)
{
var orderLines = datagrid.ItemsSource as ObservableCollection<OrderProductLine>;
if (e.Column.Header.ToString() == "Quantity")
{
var contentPresenter = e.EditingElement as ContentPresenter;
var editingTextBox = new TextBox();
editingTextBox = FindVisualChild<TextBox>(contentPresenter);
if (editingTextBox != null)
{
editingTextBox.Focus();
editingTextBox.SelectAll(); // Select all text in the TextBox
}
}
}
private void Datagrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
var view = AssociatedObject as NewOrderUserControl;
var viewModel = view.DataContext as NewOrderUserControlViewModel;
datagridCurrentItem = datagrid.CurrentItem as OrderProductLine;
var currentCellInfo = datagrid.CurrentCell;
var row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(currentCellInfo.Item);
var dataGridCell = GetCell(datagrid, row, datagrid.Columns.IndexOf(currentCellInfo.Column));
var dataGrid = FindParent<DataGrid>(dataGridCell);
var currentColumn = datagrid.CurrentCell.Column;
if (dataGridCell.IsEditing)
{
CanShowOrderNote = false;
if (e.Key == Key.Right)
{
if (IsColumnsEnabled)
{
//MoveToNextCellWithCurrentCellInfo(dataGrid, currentCellInfo);
}
}
}
else // !dataGridCell.IsEditing
{
CanShowOrderNote = true;
if (Keyboard.Modifiers == ModifierKeys.Control)
{
// If Control is pressed, do not process the 'N' key for editing
if (e.Key == Key.N)
{
// Optionally handle the Control + N case here
return; // Exit early if Control + N is pressed
}
}
if (IsEditingKey(e.Key))
{
if (datagrid.CurrentColumn.Header.ToString() == "Name")
{
if (currentColumn is DataGridTemplateColumn && datagrid.Columns.IndexOf(currentColumn) == 1)
{
// Begin editing the cell
datagrid.BeginEdit();
// Find the AutoCompleteComboBox in the current DataGridCell
var autoCompleteComboBox = FindChild<AutoCompleteTextBox.Editors.AutoCompleteComboBox>(dataGridCell, "ProductNameCell");
// Focus the AutoCompleteComboBox if found
if (autoCompleteComboBox != null)
{
autoCompleteComboBox.Focus();
autoCompleteComboBox.Text = "";
dataGrid.BeginEdit();
}
}
}
else if (datagrid.CurrentColumn.Header.ToString() == "Quantity")
{
#region Begin edit the Quantity cell textbox
if (!dataGridCell.IsEditing)
{
dataGrid.BeginEdit();
var QuantityTextBox = FindChild<TextBox>(dataGridCell, "QuantityTextBox");
if (QuantityTextBox != null)
{
QuantityTextBox.Focus();
QuantityTextBox.Text = "";
dataGrid.BeginEdit();
}
}
#endregion
}
}
else if (e.Key == Key.Insert)
{
#region Focus on product name cell and beging editing
var datagrid = sender as DataGrid;
datagrid.SelectedCells.Clear();
var currentItem = datagrid.CurrentItem;
if (addedRowsWithCancelFlag.ContainsKey(currentItem))
{
var newOrderProductLine = new OrderProductLine { };
orderProductLines.Add(newOrderProductLine);
datagrid.ScrollIntoView(newOrderProductLine);
int rowIndex = datagrid.Items.IndexOf(newOrderProductLine);
int columnIndex = GetColumnIndexByHeader(datagrid, "Name");
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[rowIndex], datagrid.Columns[columnIndex]);
var currentCellInfo1 = datagrid.CurrentCell;
var row1 = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(currentCellInfo1.Item);
var dataGridCell1 = GetCell(datagrid, row1, datagrid.Columns.IndexOf(currentCellInfo1.Column));
var dataGrid1 = FindParent<DataGrid>(dataGridCell1);
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// Start editing mode
datagrid.BeginEdit();
// Attempt to find the AutoCompleteComboBox now that the cell is in edit mode
var autoCompleteComboBox = FindChild<AutoCompleteTextBox.Editors.AutoCompleteComboBox>(dataGridCell1, "ProductNameCell");
// If the AutoCompleteComboBox was found, focus and clear its text
if (autoCompleteComboBox != null)
{
autoCompleteComboBox.Focus();
autoCompleteComboBox.Text = "";
}
isEditingInProgress = false;
}), System.Windows.Threading.DispatcherPriority.Render);
}
#endregion
}
else if (e.Key == Key.Up)
{
if (datagrid.CurrentItem == datagrid.Items[0])
{
if (addedRowsWithCancelFlag.ContainsKey(datagrid.CurrentItem))
{
_previousColumnIndexThatHandleUpKey = _lastKnownColumnIndex;
newOrderUserControl.ClientTextBox.Focus();
}
}
}
else if (e.Key == Key.Delete)
{
var currentRow = row;
if (datagrid.Items.Count > 1)
{
if (currentRow != null)
{
newOrderUserControl.DeleteConfirmationBox.Visibility = Visibility.Visible;
newOrderUserControl.DeleteConfirmationBox.NoButton.Focus();
// Optionally highlight the row to be deleted
row.Background = new SolidColorBrush(System.Windows.Media.Colors.MediumVioletRed);
e.Handled = true;
foreach (UIElement element in newOrderUserControl.MainGrid.Children) // Adjust MainGrid to your parent container
{
// Check if the element is not the DeleteConfirmationBox
if (element != newOrderUserControl.DeleteConfirmationBox)
{
element.IsEnabled = false;
}
}
}
}
}
else if (e.Key == Key.Escape)
{
viewModel.OpenOrderPaymentPopupWindowCommand.Execute(null);
//Dispatcher.BeginInvoke(new Action(() =>
//{
// e.Handled = true;
// var selectedCustomer = viewModel.SelectedCustomer;
// var amount = viewModel.OrderTotal; // Assuming you want to pass the order total as the amount.
// //var popViewModel = new PaymentPopupViewModel<Customer>(selectedCustomer, amount);
// //var popView = new PaymentPopupWindow(viewModel);
// //popView.Owner = Application.Current.MainWindow;
// //popView.ShowDialog();
// e.Handled = true;
//}));
}
}
}
private void Datagrid_CellEditEnding(object? sender, DataGridCellEditEndingEventArgs e)
{
var editingTextBox = new TextBox();
var contentPresenter = e.EditingElement as ContentPresenter;
if (e.EditingElement is not TextBox)
{
editingTextBox = FindVisualChild<TextBox>(contentPresenter);
}
if (e.EditAction == DataGridEditAction.Commit)
{
var editedRow = e.Row.Item;
var currentHeaderName = e.Column.Header.ToString();
//if (addedRows.Contains(editedRow))
if (addedRowsWithCancelFlag.ContainsKey(editedRow))
{
if (currentHeaderName == "Name")
{
if (string.IsNullOrWhiteSpace(editingTextBox?.Text) ||
viewModel.AvailableProducts.FirstOrDefault(c => c.ProductName.Equals(editingTextBox.Text, StringComparison.InvariantCultureIgnoreCase)) == null)
{
DisableColumns(datagrid, new string[] { "Quantity", "Q/U", "Price" });
e.Cancel = true;
Dispatcher.BeginInvoke(new Action(() =>
{
ProductNameCellText?.Focus();
}), System.Windows.Threading.DispatcherPriority.Input);
}
else
{
#region Setting orderline product to the selected product in the viewmodel that comes from the xaml
var orderLine = e.Row.Item as OrderProductLine;
var selectedProduct = viewModel.AvailableProducts
.FirstOrDefault(p => p.ProductName.Equals(editingTextBox.Text, StringComparison.InvariantCultureIgnoreCase));
orderLine.Product = selectedProduct;
orderLine.ProductId = selectedProduct.ProductId;
orderLine.ProductName = selectedProduct.ProductName;
orderLine.Price = selectedProduct.Price;
orderLine.QuantityPerUnit = selectedProduct.QuantityPerUnit;
#endregion
EnableColumns(datagrid, new string[] { "Quantity", "Q/U", "Price" });
int currentRowIndex = datagrid.Items.IndexOf(e.Row.Item);
int currentColumnIndex = datagrid.Columns.IndexOf(e.Column);
// Use BeginInvoke to ensure this runs after the current cell edit operation is complete
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// Keep the current cell selected
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[currentRowIndex], datagrid.Columns[currentColumnIndex]);
datagrid.SelectedCells.Clear();
datagrid.SelectedCells.Add(datagrid.CurrentCell);
// Ensure the cell gets focus
DataGridCell cell = GetCell(datagrid, e.Row, currentColumnIndex);
if (cell != null)
{
cell.Focus();
Keyboard.Focus(cell);
}
// If you want to allow editing immediately, you can call BeginEdit
// datagrid.BeginEdit();
}), System.Windows.Threading.DispatcherPriority.Input);
}
}
else
{
int currentRowIndex = datagrid.Items.IndexOf(e.Row.Item);
int currentColumnIndex = datagrid.Columns.IndexOf(e.Column);
// Use BeginInvoke to ensure this runs after the current cell edit operation is complete
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// Keep the current cell selected
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[currentRowIndex], datagrid.Columns[currentColumnIndex]);
datagrid.SelectedCells.Clear();
datagrid.SelectedCells.Add(datagrid.CurrentCell);
// Ensure the cell gets focus
DataGridCell cell = GetCell(datagrid, e.Row, currentColumnIndex);
if (cell != null)
{
cell.Focus();
Keyboard.Focus(cell);
}
// If you want to allow editing immediately, you can call BeginEdit
// datagrid.BeginEdit();
}), System.Windows.Threading.DispatcherPriority.Input);
}
}
// Else not contained
else
{
if (currentHeaderName == "Name")
{
if (string.IsNullOrWhiteSpace(editingTextBox?.Text) ||
viewModel.AvailableProducts.FirstOrDefault(c => c.ProductName.Equals(editingTextBox.Text, StringComparison.InvariantCultureIgnoreCase)) == null)
{
var productNameCellText = FindChild<TextBox>(datagrid, "PART_Editor");
_cachedProductNameCellText = productNameCellText;
DisableColumns(datagrid, new string[] { "Quantity", "Q/U", "Price" });
e.Cancel = true;
Dispatcher.BeginInvoke(new Action(() =>
{
ProductNameCellText?.Focus();
}), System.Windows.Threading.DispatcherPriority.Input);
}
else
{
#region Setting orderline product to the selected product in the viewmodel that comes from the xaml
var orderLine = e.Row.Item as OrderProductLine;
var selectedProduct = viewModel.AvailableProducts
.FirstOrDefault(p => p.ProductName.Equals(editingTextBox.Text, StringComparison.InvariantCultureIgnoreCase));
orderLine.Product = selectedProduct;
orderLine.ProductId = selectedProduct.ProductId;
orderLine.ProductName = selectedProduct.ProductName;
orderLine.Price = selectedProduct.Price;
orderLine.QuantityPerUnit = selectedProduct.QuantityPerUnit;
orderLine.Quantity = default(int);
#endregion
EnableColumns(datagrid, new string[] { "Quantity", "Q/U", "Price" });
MoveToNextCell(datagrid, e); // frist one
//var currentCellInfo = datagrid.CurrentCell;
//var row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(currentCellInfo.Item);
//var dataGridCell = GetCell(datagrid, row, datagrid.Columns.IndexOf(currentCellInfo.Column));
//var dataGrid = FindParent<DataGrid>(dataGridCell);
//if (!dataGridCell.IsEditing)
//{
// Application.Current.Dispatcher.BeginInvoke(new Action(() =>
// {
// dataGrid.BeginEdit();
// var QuantityTextBox = FindChild<TextBox>(dataGridCell, "QuantityTextBox");
// if (QuantityTextBox != null)
// {
// QuantityTextBox.Focus();
// QuantityTextBox.Text = "";
// dataGrid.BeginEdit();
// }
// }), System.Windows.Threading.DispatcherPriority.Render);
//}
}
}
else if (currentHeaderName == "Price")
{
if (!isEditingInProgress)
{
//addedRows.Add(editedRow);
addedRowsWithCancelFlag.Add(editedRow, false);
//FocusOnCell(datagrid, e.Row.AlternationIndex, 4);
}
}
else if (currentHeaderName == "Quantity")
{
if (!isEditingInProgress)
{
if (string.IsNullOrWhiteSpace(editingTextBox?.Text))
{
e.Cancel = true;
}
else
{
MoveToNextCell(datagrid, e);
}
}
}
else
{
if (!isEditingInProgress)
{
MoveToNextCell(datagrid, e);
}
}
}
}
else if (e.EditAction == DataGridEditAction.Cancel)
{
var editedRow = e.Row.Item;
var currentHeaderName = e.Column.Header.ToString();
if (currentHeaderName == "Name")
{
int currentRowIndex = e.Row.GetIndex();
int lastRowIndex = datagrid.Items.Count - 1;
if (currentRowIndex == 0)
{
e.Cancel = true;
}
else if (addedRowsWithCancelFlag.ContainsKey(editedRow))
{
// If the flag is false, prevent canceling the row
if (!addedRowsWithCancelFlag[editedRow])
{
e.Cancel = true; // Prevent canceling
}
else
{
// Allow canceling
e.Cancel = false;
}
}
else
{
e.Cancel = false;
orderProductLines.RemoveAt(orderProductLines.Count - 1);
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[0], datagrid.Columns[1]);
datagrid.SelectedCells.Clear();
datagrid.SelectedCells.Add(datagrid.CurrentCell);
}
}
else
{
if (!addedRowsWithCancelFlag.ContainsKey(editedRow))
{
isEditingInProgress = true;
int currentRowIndex = datagrid.Items.IndexOf(datagrid.CurrentItem);
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[currentRowIndex], datagrid.Columns[1]);
var currentCellInfo = datagrid.CurrentCell;
var row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(currentCellInfo.Item);
var dataGridCell = GetCell(datagrid, row, datagrid.Columns.IndexOf(currentCellInfo.Column));
var dataGrid = FindParent<DataGrid>(dataGridCell);
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// Start editing mode
datagrid.BeginEdit();
// Attempt to find the AutoCompleteComboBox now that the cell is in edit mode
var autoCompleteComboBox = FindChild<AutoCompleteTextBox.Editors.AutoCompleteComboBox>(dataGridCell, "ProductNameCell");
// If the AutoCompleteComboBox was found, focus and clear its text
if (autoCompleteComboBox != null)
{
autoCompleteComboBox.Focus();
autoCompleteComboBox.Text = "";
}
isEditingInProgress = false;
}), System.Windows.Threading.DispatcherPriority.Render);
}
else
{
}
}
}
}
private void ProductNameCell_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textbox = sender as TextBox;
var enteredProduct = textbox?.Text;
var newOrderControl = FindParent<NewOrderUserControl>(textbox);
if (string.IsNullOrWhiteSpace(enteredProduct) ||
viewModel.AvailableProducts.FirstOrDefault(c => c.ProductName.Equals(enteredProduct, StringComparison.InvariantCultureIgnoreCase)) == null)
{
e.Handled = true;
}
}
#endregion
#endregion
#region Helper methods
private void MoveToNextCell(DataGrid datagrid, DataGridCellEditEndingEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
int currentRowIndex = datagrid.Items.IndexOf(e.Row.Item);
int currentColumnIndex = datagrid.Columns.IndexOf(e.Column);
if (currentColumnIndex + 1 < datagrid.Columns.Count)
{
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[currentRowIndex], datagrid.Columns[currentColumnIndex + 1]);
datagrid.BeginEdit();
}
}), System.Windows.Threading.DispatcherPriority.Input);
//if (Application.Current.Dispatcher.CheckAccess())
//{
// int currentRowIndex = datagrid.Items.IndexOf(e.Row.Item);
// int currentColumnIndex = datagrid.Columns.IndexOf(e.Column);
// if (currentColumnIndex + 1 < datagrid.Columns.Count)
// {
// datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[currentRowIndex], datagrid.Columns[currentColumnIndex + 1]);
// datagrid.BeginEdit();
// }
//}
//else
//{
// Application.Current.Dispatcher.BeginInvoke(new Action(() =>
// {
// int currentRowIndex = datagrid.Items.IndexOf(e.Row.Item);
// int currentColumnIndex = datagrid.Columns.IndexOf(e.Column);
// if (currentColumnIndex + 1 < datagrid.Columns.Count)
// {
// datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[currentRowIndex], datagrid.Columns[currentColumnIndex + 1]);
// datagrid.BeginEdit();
// }
// }), System.Windows.Threading.DispatcherPriority.Input);
//}
}
private bool DisableColumns(DataGrid datagrid, string[] columnHeaders)
{
foreach (var columnHeader in columnHeaders)
{
var column = datagrid.Columns.FirstOrDefault(c => c.Header.ToString() == columnHeader);
if (column != null)
{
// Disable the column (You may need to adjust this logic based on your requirements)
column.IsReadOnly = true; // Set to read-only instead of IsEnabled
}
}
return IsColumnsEnabled = false;
}
private bool EnableColumns(DataGrid datagrid, string[] columnHeaders)
{
foreach (var columnHeader in columnHeaders)
{
var column = datagrid.Columns.FirstOrDefault(c => c.Header.ToString() == columnHeader);
if (column != null)
{
// Enable the column
column.IsReadOnly = false;
}
}
return IsColumnsEnabled = true;
}
private T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
// Confirm parent is valid
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T childType && !string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
if (frameworkElement != null && frameworkElement.Name == childName)
{
foundChild = (T)child;
break;
}
}
// Recursively drill down the tree
foundChild = FindChild<T>(child, childName);
if (foundChild != null) break;
}
return foundChild;
}
private MenuItem FindMenuItem(MenuItem parent, string name)
{
return parent.Items.OfType<MenuItem>().FirstOrDefault(item => item.Name == name);
}
private T FindParent<T>(DependencyObject child) where T : DependencyObject
{
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
if (parentObject == null) return null;
if (parentObject is T parent) return parent;
return FindParent<T>(parentObject);
}
private T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is T childOfType)
{
return childOfType;
}
else
{
T childItem = FindVisualChild<T>(child);
if (childItem != null)
{
return childItem;
}
}
}
return null;
}
public void FocusOnCell(DataGrid dataGrid, int rowIndex, int columnIndex)
{
// Ensure the row index and column index are valid
if (rowIndex < 0 || rowIndex >= dataGrid.Items.Count || columnIndex < 0 || columnIndex >= dataGrid.Columns.Count)
return;
// Scroll the DataGrid so the row is visible
dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);
// Get the DataGridRow
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
if (row == null)
{
// Try to bring the row into view and generate its container
dataGrid.UpdateLayout();
row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex);
}
if (row != null)
{
// Get the specific cell from the row
DataGridCell cell = GetCell(dataGrid, row, columnIndex);
if (cell != null)
{
// Set focus on the cell
dataGrid.BeginEdit(); // Start editing mode
// Use Dispatcher to set focus to the cell
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
cell.Focus(); // Focus the cell
Keyboard.Focus(cell); // Ensure keyboard focus is set
}), System.Windows.Threading.DispatcherPriority.Input);
}
}
}
public DataGridCell GetCell(DataGrid dataGrid, DataGridRow row, int columnIndex)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
// Try to get the cell directly from the presenter
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (cell == null)
{
// If the cell is null, force the cell to be generated by scrolling it into view
dataGrid.ScrollIntoView(row, dataGrid.Columns[columnIndex]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}
return cell;
}
public T GetVisualChild<T>(Visual parent) where T : Visual
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
Visual child = (Visual)VisualTreeHelper.GetChild(parent, i);
if (child != null && child is T)
{
return (T)child;
}
else
{
T childOfChild = GetVisualChild<T>(child);
if (childOfChild != null)
{
return childOfChild;
}
}
}
return null;
}
private bool IsEditingKey(Key key)
{
// Define which keys should trigger the editing
return key >= Key.A && key <= Key.Z || // Letters
key >= Key.D0 && key <= Key.D9 || // Numbers (Top row)
key >= Key.NumPad0 && key <= Key.NumPad9 || // Numbers (NumPad)
key == Key.Space; // Space
}
public void SelectCell(DataGrid dataGrid, int rowIndex, int columnIndex)
{
// Ensure the row index and column index are valid
if (rowIndex < 0 || rowIndex >= dataGrid.Items.Count || columnIndex < 0 || columnIndex >= dataGrid.Columns.Count)
return;
// Scroll the DataGrid so the row is visible
dataGrid.ScrollIntoView(dataGrid.Items[rowIndex]);
// Clear any previously selected cells
dataGrid.SelectedCells.Clear();
// Create a DataGridCellInfo for the specified cell
var cellInfo = new DataGridCellInfo(dataGrid.Items[rowIndex], dataGrid.Columns[columnIndex]);
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
dataGrid.SelectedCells.Add(cellInfo);
dataGrid.Focus();
Keyboard.Focus(dataGrid);
dataGrid.CurrentCell = cellInfo;
}), System.Windows.Threading.DispatcherPriority.Input);
}
private int GetColumnIndexByHeader(DataGrid datagrid, string headerName)
{
for (int i = 0; i < datagrid.Columns.Count; i++)
{
if (datagrid.Columns[i].Header.ToString() == headerName)
{
return i; // Return the index if the header matches
}
}
return -1; // Return -1 if no match is found
}
private void MoveToNextCellWithCurrentCellInfo(DataGrid dataGrid, DataGridCellInfo currentCellInfo)
{
int currentRowIndex = dataGrid.Items.IndexOf(currentCellInfo.Item);
int currentColumnIndex = dataGrid.Columns.IndexOf(currentCellInfo.Column);
if (currentColumnIndex + 1 < dataGrid.Columns.Count)
{
// Move to the next column in the same row
dataGrid.CurrentCell = new DataGridCellInfo(dataGrid.Items[currentRowIndex], dataGrid.Columns[currentColumnIndex + 1]);
dataGrid.BeginEdit();
}
else if (currentRowIndex + 1 < dataGrid.Items.Count)
{
// Move to the first column of the next row
dataGrid.CurrentCell = new DataGridCellInfo(dataGrid.Items[currentRowIndex + 1], dataGrid.Columns[0]);
dataGrid.BeginEdit();
}
}
private void FocusAndBeginEdit(DataGrid datagrid, DataGridRow row, int columnIndex)
{
// Get the row index from the DataGrid's ItemContainerGenerator
int rowIndex = datagrid.ItemContainerGenerator.IndexFromContainer(row);
// Ensure the row index is valid
if (rowIndex < 0 || rowIndex >= datagrid.Items.Count) return;
DataGridCell cell = GetCell(datagrid, row, columnIndex);
if (cell != null)
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
datagrid.CurrentCell = new DataGridCellInfo(datagrid.Items[rowIndex], datagrid.Columns[columnIndex]);
datagrid.SelectedCells.Clear();
datagrid.SelectedCells.Add(datagrid.CurrentCell);
cell.Focus();
Keyboard.Focus(cell);
// Optionally, uncomment this line if immediate edit is needed:
// datagrid.BeginEdit();
}), System.Windows.Threading.DispatcherPriority.Input);
}
}
private bool IsChildOf(DependencyObject parent, DependencyObject child)
{
if (parent == null || child == null)
return false;
DependencyObject currentParent = child;
// Traverse up the visual tree until we find the parent or hit the root element
while (currentParent != null)
{
if (currentParent == parent)
return true;
currentParent = VisualTreeHelper.GetParent(currentParent);
}
return false;
}
#endregion
}
}