Oscar
Oscar

Reputation: 1147

How to edit a value from a DataGrid in WPF?

My data grid has in itemsSource a list of Groups:

public class Group : INotifyPropertyChanged

{
    public Group() { }
    public Group(int groupID, string groupName)
    {
        this.GroupID = groupID;
        this.GroupName = groupName;
    }

    private int _groupID;
    public int GroupID
    {
        get { return _groupID; }
        set
        {
            _groupID = value;
            OnPropertyChanged("GroupID");
        }
    }

    private string _groupName;
    public string GroupName
    {
        get { return _groupName; }
        set
        {
            _groupName = value;
            OnPropertyChanged("GroupName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

But I realize that when I edit a cell, I need to press Enter key to fired OnPropertyChanged from Group class. So if I only edit the cell value don't fire the event unless I press Enter key.

Is possible when I edit the cell value without press Enter key, get fired the event?

Upvotes: 1

Views: 609

Answers (3)

blindmeis
blindmeis

Reputation: 22445

By default the WPF DataGrid will commit a row when focus is lost on the row, the ‘Enter’ key is pressed, tabbing to the next row, or programmatically calling commit on the row.

some more information you get here

Upvotes: 0

Kevin
Kevin

Reputation: 3509

You need to use UpdateSourcetrigger within your xaml

There are three different kinds:

  1. PropertyChanged – The source is updated whenever the target property value changes.
  2. LostFocus – The source is updated when target property changes and target object looses focus.
  3. Explicit – The source is updated when explicit call is made to update using “BindingExpression.UpdateSource”.

Upvotes: 0

Steven Magana-Zook
Steven Magana-Zook

Reputation: 2759

You need to change the default two-way binding to be UpdateSourceTrigger="PropertyChanged".

Example from MSDN:

<TextBox Name="itemNameTextBox"
         Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}" />

Example: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx

UpdateSourceTrigger Binding Property Page: http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.aspx

Upvotes: 4

Related Questions