WPF DataGrid switch template between view mode and edit mode

If you have a WPF DataGrid left of the window with an area to the right to display the selected record. The selected entry consists of Textbox es and ComboBox es, which are disabled until the edit button is pressed. Everything works as expected.

However, when changing the SelectedItem DataGrid , it seems a little inconvenient to populate ComboBox es. Lighter controls, such as TextBlock , can be used until the "Edit" button is clicked, then TextBlock can be disabled for ComboBox es.

I am sure that this can be done with some kind of template, but when I tried to experiment with it, all the events related to ComboBox es report an error because they are no longer present, because they are replaced by TextBlocks in "view mode".

I’m probably mistaken, so some recommendations will be appreciated.

+4
source share
3 answers

excellent article here

To apply one-click editing to all cells in a DataGrid

  • Paste the style below into the Resources of your DataGrid.
  • Paste this method into code

To apply single editing only to specific cells in a DataGrid

  • Set x: style key (e.g.)
  • Paste the style into the Resources of your DataGrid
  • Apply a style to the CellStyle property for columns that you would like to edit with one click (for example)
  • Paste this method into the code located behind

     // // SINGLE CLICK EDITING // private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DataGridCell cell = sender as DataGridCell; if (cell != null && !cell.IsEditing && !cell.IsReadOnly) { if (!cell.IsFocused) { cell.Focus(); } DataGrid dataGrid = FindVisualParent<DataGrid>(cell); if (dataGrid != null) { if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow) { if (!cell.IsSelected) cell.IsSelected = true; } else { DataGridRow row = FindVisualParent<DataGridRow>(cell); if (row != null && !row.IsSelected) { row.IsSelected = true; } } } } } static T FindVisualParent<T>(UIElement element) where T : UIElement { UIElement parent = element; while (parent != null) { T correctlyTyped = parent as T; if (correctlyTyped != null) { return correctlyTyped; } parent = VisualTreeHelper.GetParent(parent) as UIElement; } return null; } 
+3
source

The ContentTemplateSelector property should allow you to select one or more templates depending on the current mode (view / edit)

+1
source

The marked answer link is dead.

This may help instead: http://wpf.codeplex.com/wikipage?title=Single-Click%20Editing

+1
source

Source: https://habr.com/ru/post/1285673/


All Articles