SNS
SNS

Reputation: 405

How to do editable data grid in wpf using mvvm?

I want to use a editable data grid, to add, edit data. Is it possible with wpf? Can some one give an the example?

Upvotes: 16

Views: 48002

Answers (2)

Omri Btian
Omri Btian

Reputation: 6547

DataGrid controls has all that functionality built-in. You can set the properties CanUserAddRows to true to allow user to add rows.

DataGrid is editable by default, where each column has an edit control which lets you edit its value. By default the DataGrid automatically generates columns for every property in your Model, so you don't even have to define it's columns.

Here are some good links with detailed examples you can look into:

http://wpftutorial.net/DataGrid.html

http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples

http://www.c-sharpcorner.com/UploadFile/mahesh/datagrid-in-wpf/

Good luck

Upvotes: 21

Kumareshan
Kumareshan

Reputation: 1341

Have a Xaml as below

<Window x:Class="DatGrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:DatGrid">
<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>
<StackPanel/>
    <DataGrid ItemsSource="{Binding Path=Values}"></DataGrid>
</StackPanel>
</Window>

In the ViewModel is very simple some thing like below

class ViewModel
{
    public ObservableCollection<Example> Values
    {
        get;
        set;
    }
}
public class Example
{
    public string A
    {
        get;
        set;
    }
    public string B
    {
        get;
        set;
    }
}

In the view you can always see a empty row you can just click and type something and press enter it'll get updated to the ViewModel

Upvotes: 3

Related Questions