Reputation: 1127
I've already made a WPF application without MVVM and I do update my rows by using some event such CellEditEnding, but Now I want to do the same thing in MVVM so I'm not going to use any event and I should do it in my ViewModel.
How Can I do it? ( I like a way that just updating the rows which are changed). I want to use Datagrid's feature instead of using any button such as Update button.
Upvotes: 1
Views: 2136
Reputation: 1904
The big "thing" as I see it with WPF and MVVM is databinding. So instead of having to tell the GUI exactly what to do (ie CellEditEnding etc), you leave the editing to GUI (View) and just handle the data in Viewmodel.
As you can see in the sample below (which is as simple as it comes), there is no code about how to do things like updating a cell, there is only a databinding - binding the ObservableCollection to DataGrid´s ItemsSource
Example:
<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication12="clr-namespace:WpfApplication12"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<WpfApplication12:MainWindowViewModel />
</Window.DataContext>
<Grid>
<DataGrid ItemsSource="{Binding PersonList}">
</DataGrid>
</Grid>
</Window>
C# code-behind:
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
PersonList = new ObservableCollection<Person>()
{
new Person(){Name="Bobby"}
};
}
public ObservableCollection<Person> PersonList { get; set; }
public void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
}
public void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
As I said earlier, this is as simple as it gets just to get you started.
Upvotes: 1