Search code examples
c#wpfxamlmvvmdatagridtextcolumn

Executing a method on current row when editing a DataGridTextColumn


I currently have a DataGrid bound to a Person object:

<DataGrid ItemsSource="{Binding Person}" Width="1700" Height="840" AutoGenerateColumns="False" CanUserAddRows="true" ...>
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Select" Binding="{Binding IsChecked}"/>
        <DataGridTextColumn Header="Gender" Binding="{Binding Gender}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Username" Binding="{Binding Username}" />
        ...
    </DataGrid.Columns>
</DataGrid>

When the user edits the grid and adds a new username, I need to fire a method which goes off to the database and populate the other information (Gender, etc.) based on the new username.

Currently, the user enters a username, checks the check box associated with that row, and clicks a button to populate the rest of the data. I am trying to get rid of these extra 2 steps as this should happen automatically.

I am using the MVVM pattern for this.

Thank you for any help.


Solution

  • As you are using the MVVM pattern I assume the "Person" class will be having a property for "Username". Implement the INotifyPropertyChanged interface and change the property to a normal property if it is an auto property and call the database update after the property has been notified with any checks that you need. Something like this:

        private string username;
        public string Username
        {
            get
            {
                return username;
            }
            set
            {
                username= value;
                NotifyPropertyChanged("Username");
                if (<condition>)
                   PopulateData();
            }
        }
    

    In the xaml make the following changes:

    <DataGridTextColumn Header="Username" Binding="{Binding Username, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" />
    

    This will call the setter of the Username property as soon as the cell loses it's focus and the data will get populated.