Search code examples
wpfdatagridbehaviordatagridtextcolumn

Behavior to insert and select text into a DataGrid Text cell when editing


I'm attempting to create a behavior that pre-fills and selects text into a DataGrid's text cell when the cell is being edited. The behavior is as follow:

public class AutoFillBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.BeginningEdit += OnBeginEdit;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.BeginningEdit -= OnBeginEdit;
        base.OnDetaching();
    }

    private void OnBeginEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        if (e.Column.Header.ToString() == "Name")
        {
            var grid = (sender as DataGrid);
            var rowId = (grid.Columns[0].GetCellContent(e.Row) as TextBlock).Text;
            string name = null;
            DLL.FieldNames.TryGetValue(rowId, out name);
            if (!string.IsNullOrWhitespace(name)) {
                var rowData = (from IDataTable item in grid.Items
                               where item.Id == rowId
                               select item).First();
                rowData.Name = name;
                // Would like to select text in textbox here
            }
        }
    }
}

I have the part where it fills in the cell being edited, but how do I select all the text after inserting it? The problem I'm having is the content of the current cell is a TextBlock when the BeginningEdit event is active. If it were a TextBox I could easily invoke the .SelectAll() method. However, per MSDN a cell in a DataGridTextColumn is a TextBlock before/after edit, and a TextBox during edit.


Solution

  • This should work:

    public class AutoFillBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.PreparingCellForEdit += OnPreparingCellForEdit;
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.PreparingCellForEdit -= OnPreparingCellForEdit;
            base.OnDetaching();
        }
    
        private void OnPreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            if (e.Column.Header.ToString() == "Name")
            {
                //...
    
                TextBox textBox = e.EditingElement as TextBox;
                if (textBox != null)
                {
                    textBox.Text = "...";
                    textBox.SelectAll();
                }
            }
        }
    }