如何使用mvvm数据绑定更新Datagrid

时间:2016-01-26 17:52:49

标签: c# wpf mvvm data-binding datagrid

我有3个文本框,当用户在其中输入值并按下保存按钮时,他们应该将它们包含的数据添加到数据网格中。

每件事情都很好并且绑定到文本框和按钮很好但我不明白如何使用在文本框中输入的值用户来更新数据网格。

我的完整代码在这里:

  <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是:

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));
        }
    }
}

我的意思是如何绑定MyAction()中的datagrid,以便将所有三个文本框字符串添加到相应的列中?

1 个答案:

答案 0 :(得分:1)

正如其他人在评论中建议我不确定Dgrid代表什么,但我认为一个简单的例子应该有所帮助:

这只是一个带有DataGrid,TextBox和按钮的窗口。当您在数据网格中键入内容并按下按钮时,它会将值添加到数据网格中。它完成了MVVM,我希望这能证明这个过程。 (。NET 4.6语法。如果它没有工作,则更改可观察集合并将其创建移动到构造函数)

<强> 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);
        }
    }
}