Select and edit the first DataGrid cell in a newly added row

Viewed 1258

I have a data grid with "CanUserAddRows=False" and I want to add a new row on button click and start editing it. Here is the xaml:

<Window x:Class="TestDataGrid2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestDataGrid2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Content="Add Item" HorizontalAlignment="Left" Click="Button_Click"/>
        <DataGrid ItemsSource="{Binding Items}" Grid.Row="1" Name="MyGrid" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Value" Binding="{Binding Value}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

Here is the code behind:

using System.Windows;
using System.Windows.Controls;

namespace TestDataGrid2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var mainViewModel = DataContext as MainViewModel;
            if (mainViewModel != null)
                mainViewModel.AddItem();

            var grid = MyGrid;
            var cell = new DataGridCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
            grid.CurrentCell = cell;
            grid.BeginEdit();
        }
    }
}

And this is my view model:

using System.Collections.ObjectModel;

namespace TestDataGrid2
{
    public class MainViewModel
    {
        public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<Item>();

        public void AddItem()
        {
            Items.Add(new Item { Value = "New Item" });
        }
    }

    public class Item
    {
        public string Value { get; set; }
    }
}

For some reason I can't start editing the cell in a newly added row. I suspect that it might be because at the moment I call BeginEdit the visual element doesn't exist yet. Is there a way to force the cell to load in order to be able to focus and edit it? Or is there an event I can subscribe to when the cell is ready?

2 Answers
Related