无法将可观察的集合绑定到MVVM中的数据网格 [英] unable to bind the observablecollection to the datagrid in MVVM

查看:118
本文介绍了无法将可观察的集合绑定到MVVM中的数据网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是MVVM的全新功能.我试图将数据从sqlserver绑定到WPF中的Datagrid并对其执行编辑,更新和删除操作.现在,无法使用MVVM中的可观察集合将数据从sqlserver至少绑定到datagrid....有人请帮助我解决它,也请让我知道如何对同一datagrid实施编辑,更新和删除操作.... am在实现MVVM体系结构时完全感到困惑..

使用以下代码,我可以将数据绑定到"Empdata"(observablecollection),但根本不会显示datagrid.

以下是我的xaml代码:

am completely new to MVVM. I was trying to bind the data from sqlserver to the Datagrid in WPF and perform Edit, update and delete operations on it. now, am unable to bind the data from sqlserver to datagrid atleast using observable collection in MVVM.... someone please help me out to resolve it and also kindly let me know how to implement the edit,update and delete operations for the same datagrid....am totally getting confused implementing the MVVM architecture..

with the following code i could bind the data to "Empdata"(observablecollection) but the datagrid is not being displayed at all.

the following is my xaml code :

<datagrid itemssource="{Binding Path=Empdata}" x:name="dtgrdemp" xmlns:x="#unknown">
             AutoGenerateColumns="False"
             SelectionMode="Single"
             SelectionUnit="FullRow"
             GridLinesVisibility="Horizontal"
             CanUserDeleteRows="True"
             CanUserAddRows="False">
            <datagrid.columns>
                <datagridtextcolumn header="Name" width="SizeToCells" minwidth="125" binding="{Binding Path=Ename}" />
                <datagridtextcolumn header="Age" width="SizeToCells" minwidth="200" binding="{Binding Path=Eage}" />
                <datagridtextcolumn header="Description" width="SizeToCells" minwidth="200" binding="{Binding Path=Edescription}" />
            </datagrid.columns></datagrid>



以下是我的"view"代码,其中我上了一个人



the following is my code for "view" where i took a class as person

 public class Person : INotifyPropertyChanged, IDataErrorInfo
{
    private string names;

    public string Names
    {
        get { return names; }
        set
        {
            names = value;
            OnPropertyChanged("Names");
        }
    }

    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            age = value;
            OnPropertyChanged("Age");
        }
    }

    private string description;

    public string Description
    {
        get { return description; }
        set
        {
            description = value;
            OnPropertyChanged("Description");
        }
    }



    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyname)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyname));
    }
 public string Error
    {
        get { return null; }
    }

    public string this[string columnName]
    {
        get
        {
            string error = null;
            switch (columnName)
            {
                case "Names":
                    if (string.IsNullOrEmpty(names))
                    {
                        error = "First Name required";
                    }
                    break;

                case "Age":
                    if ((age < 18) || (age > 85))
                    {
                        error = "Age out of range.";
                    }
                    break;
                case "Description":
                    if (string.IsNullOrEmpty(description))
                    {
                        error = "Last Name required";
                    }
                    break;
            }
            return (error);


        }
    }



以下是我的"ViewModel"类的代码



the following is my code for "ViewModel" class

public class MainViewModel :INotifyPropertyChanged
{
    string con = ConfigurationSettings.AppSettings["ConnectionStrings"];
    ObservableCollection<empinfo> Empdata= new ObservableCollection<empinfo>();


    private Person empperson;

    public Person Empperson
    {
        get { return empperson; }
        set { empperson = value; }
    }

    public MainViewModel()
    {
        initializeload();
    }

    private void initializeload()
    {
        DataTable dt = new DataTable();
        Empdata = new ObservableCollection<empinfo>();
        Empdata.Add(new EmpInfo(dt));

    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyname)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyname));
    }
}
the following is the code for EmpInfo.cs class

 public EmpInfo(DataTable dt)
    {
        SqlConnection sqlcon = new SqlConnection(con);
        sqlcon.Open();
        SqlDataAdapter da = new SqlDataAdapter("Select Ename,Eage,Edescription from EmployeeTable", sqlcon);
        da.Fill(dt);
        this.dt = dt;
    }
the following is the code in Appxaml.cs

 protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        var mainWindow = new MainWindow();
        var viewModel = new MainViewModel();
        mainWindow.DataContext = viewModel;
        mainWindow.Show();
    }</empinfo></empinfo></empinfo>



在此先感谢.



Thanks in advance.

推荐答案

首先,绑定数据集和数据表并不是WPF应用程序中的最佳解决方案,您确实应该使用ADO.Net和将您的数据库信息转换为CLR objects,在本例中为ObservableCollection<employees>.然后,您可以将datagrid绑定到集合,而不是数据表.其次,关于编辑网格中的员工记录,您应该具有特定的按钮,用户可以使用它们来编辑,保存和取消编辑.这些按钮将绑定到视图模型中的ICommand属性,然后将使用ADO.Net调用数据访问层来更新或插入记录.

希望这对
To start with, binding to datasets and datatables is not the best solution in WPF applications, you really should use ADO.Net and a DataReader to convert your database info into CLR objects, in this case an ObservableCollection<employees>. You can then bind you datagrid to the collection, rather than a datatable. Secondly, with regard to editing an employees record in the grid, you should have specific buttons which the user can use to edit, save and cancel edit. These buttons would be bound to ICommand properties in your viewmodel, which would then call the data access layer to update or insert records using ADO.Net.

Hope this helps


公开MainViewModel.Empdata有所帮助,并且不要将其初始化两次,这不是多余的错误.

我的文章现在或将来也可能为您提供帮助
调试WPF数据绑定 [
Make MainViewModel.Empdata public, and do not initialize it twice it''s not an error just redundant.

My article might also be able to help you now and in the future
Debugging WPF data bindings[^]
It might be tricky to understnd if you''re really that new to data binding in WPF, but you''re always welcome to leave any questions you might have on the discussion of that article.


这篇关于无法将可观察的集合绑定到MVVM中的数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆