简体   繁体   中英

How Can I update a row in WPF's datagrid when I 'm implementing MVVM ? ( without any Button)

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.

  • by the way when I done it I'll go for Full CRUD system.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM