简体   繁体   中英

How to update Datagrid using mvvm databinding

I have 3 text boxes and when user enter value in them and press save button then they should add the data they contain to the data grid.

Every thing works fine and binding to the textboxes and button is done well but i do not understand how to update datagrid using the value user entered in textboxes.

My full code is here :

  <Window x:Class="WpfApplication4.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">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition Height="30"></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid Grid.Row="0">
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding TextName}" Height="20" Width="80" HorizontalAlignment="Center"></TextBox>
                <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding RollNumber}"  Height="20" Width="80"></TextBox>
                <TextBox Grid.Column="1" Grid.Row="2" Text="{Binding Class}" Height="20" Width="80"></TextBox>
                <Label Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center">Name</Label>
                <Label Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">RollNumber</Label>
                <Label Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center">Class</Label>
            </Grid>
            <Grid Grid.Row="1" >
                <Button Width="80" Height="20" Command="{Binding SaveStudentRecord}"> Save</Button>
            </Grid>
            <Grid Grid.Row="2">
                <DataGrid ItemsSource="{Binding DGrid}">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Name" Binding="{Binding  DgName}" Width="150"></DataGridTextColumn>
                        <DataGridTextColumn Header="Rollnumber" Binding="{Binding dgRollnumber}" Width="150"></DataGridTextColumn>
                        <DataGridTextColumn Header="Class" Binding="{Binding dgClass}" Width="150"></DataGridTextColumn>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </Grid>
    </Window>

ViewModel is:

class ViewModel
{
    private string textName;
    private string rollNumber;
    private string cclass;
    private RelayCommand saveStudentRecord;
    private Model editModel;
    public string TextName
    {
        get { return textName; }
        set
        {
            textName = value;
            PropertyChangedEventArgs("TextName");
        }
    }

    public string RollNumber
    {
        get { return rollNumber; }
        set
        {
            rollNumber = value;
            PropertyChangedEventArgs("RollNumber");
        }
    }

    public string Class
    {
        get { return cclass; }
        set
        {
            rollNumber = value;
            PropertyChangedEventArgs("Class");
        }
    }

    public bool canExecute { get; set; }

    public Model EditModel
    {
        get 
        {
            return editModel ; 
        }
        set 
        {
            editModel = value;
            PropertyChangedEventArgs("EditModel");
        }
    }
    public ViewModel()
    {
       canExecute = true;
    }
    public RelayCommand SaveStudentRecord
    {
        get { return saveStudentRecord = new RelayCommand(() => MyAction(), canExecute); }
    }

    private void MyAction()
    {
        string chck1 = TextName; //I see on debugging that TextName contains the text entered so how to add this text to Datagrid column
        string chck2 = Class;
        string chck3 = RollNumber;

        // How to add this data to datagrid
        MessageBox.Show("Hii");
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void PropertyChangedEventArgs(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

What exactly i mean is how to bind the datagrid inside the MyAction() such that all the three textbox strings will be added to the respective columns ?

As others have suggested in comments I'm not sure what Dgrid represents, but I think a simple example should help:

This is just a window with a DataGrid, TextBox and a button. When you type something in the datagrid and press the button it adds the value to the datagrid. It's done MVVM, I hope this demonstrates the process. (.NET 4.6 syntax. If it doesn't work change the observable collection and move the creation of it to the constructor)

MainView.xaml

<Window x:Class="WpfApplication4.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainView" Height="350" Width="525">
    <Grid>
        <DataGrid HorizontalAlignment="Left" Height="207" Margin="103,46,0,0" VerticalAlignment="Top" Width="311" ItemsSource="{Binding Stuff}" AutoGenerateColumns="false">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding}"/>
            </DataGrid.Columns>
        </DataGrid>
        <TextBox HorizontalAlignment="Left" Height="20" Margin="167,9,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="179" Text="{Binding TextValue, Mode=TwoWay}"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="351,8,0,0" VerticalAlignment="Top" Width="75" Command="{Binding GoCommand}"/>

    </Grid>
</Window>

MainViewModel.cs

using System.Collections.ObjectModel;
using System.Windows.Input;

namespace WpfApplication4
{
    public class MainViewModel
    {
        public ObservableCollection<string> Stuff { get; set; } = new ObservableCollection<string>();

        public ICommand GoCommand { get; set; }
        public string TextValue { get; set; }   

        public MainViewModel()
        {
            Stuff.Add("a");
            Stuff.Add("b");
            Stuff.Add("c");
            Stuff.Add("d");

            GoCommand = new RelayCommand((p) => Stuff.Add(TextValue));
        }
    }
}

MainView.xaml.cs

using System.Windows;

namespace WpfApplication4
{
    public partial class MainView : Window
    {
        public MainView()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
        }
    }
}

RelayCommand.cs

using System;
using System.Diagnostics;
using System.Windows.Input;

namespace WpfApplication4
{
    public class RelayCommand : ICommand
    {
        private readonly Action<object> execute;
        private readonly Predicate<object> canExecute;

        public RelayCommand(Action<object> execute) : this(execute, null)
        {
        }

        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null) throw new ArgumentNullException("execute");

            this.execute = execute;
            this.canExecute = canExecute;
        }

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return canExecute == null || canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}

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