Reputation: 455
I have a DataGrid
bound to a list of Job
Models. The Job
Model has a JobName
property.
I can tell when a row is selected because the grid's SelectedItem
is set, But when the user changes some data in the grid, I'd like to do some things in the view model.
When the user changes the JobName
on the active row in the grid, how can the View Model know about it?
Upvotes: 1
Views: 2110
Reputation: 12420
Have your model implement INotifyPropertyChanged
. Then when you fill the Job list from your DAL register your model items with your propertyChanged event handler
View Model Class:
public class JobsViewModel
{
public List<Job> Jobs { get; set; }
public JobsViewModel()
{
//Get your list of items and add your handler method for each item that is added
Jobs = new List<Job>();
Job job = new Job("Joe");
job.PropertyChanged += job_PropertyChanged;
Jobs.Add(job);
}
private void job_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
//Do stuff with job here
}
}
Job Class:
public class Job : INotifyPropertyChanged
{
private string _jobName;
public string JobName
{
get { return _jobName; }
set
{
_jobName = value;
OnPropertyChanged("JobName");
}
}
public Job(string jobName)
{
JobName = jobName;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Upvotes: 1
Reputation: 2947
Your JobName
property should something like:
public string JobName
{
get { return _jobName; }
set
{
_jobName = value;
this.OnPropertyChanged("JobName");
}
}
When user changes it the datagrid, the setter will be called and you can add some logic there. Binding should be TwoWay
(as is by default) for this to work.
If you need to listen to property changes in your viewmodel, an easy way is to add this in the constructor:
jobModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(JobModel_PropertyChanged);
Then in the JobModel_PropertyChanged
method you can check which property has changed and react.
Upvotes: 1
Reputation: 883
If there is a two way binding the JobName property setter of your JobModel instance will be invoked. If the setter raises the PropertyChanged event you can handle that event in the ViewModel by registering and unregistering the handler when the selected item changes.
Upvotes: 1