无法将observablecollection绑定到MVVM中的datagrid

时间:2011-09-13 12:01:48

标签: wpf binding mvvm datagrid

对MVVM来说是全新的。我试图将数据从sqlserver绑定到WPF中的Datagrid,并对其执行编辑,更新和删除操作。 现在,无法使用MVVM中的observable集合将数据从sqlserver绑定到datagrid .... 有人请帮我解决它,也请让我知道如何实现相同数据网格的编辑,更新和删除操作....我完全不知道实现MVVM架构。

使用以下代码我可以将数据绑定到“Empdata”(observablecollection),但数据网格根本没有显示。

以下是我的xaml代码:

<DataGrid    ItemsSource="{Binding Path=Empdata}" x:Name="dtgrdemp"
             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>

以下是我的“视图”代码,其中我将课程视为人

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”类

的代码
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));
    }
}

以下是EmpInfo.cs类的代码

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

以下是Appxaml.cs中的代码

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

3 个答案:

答案 0 :(得分:3)

您的代码Empdata.Add(new EmpInfo(dt));没有填充可观察集合Empdata

Atleast是你的构造函数

   public EmpInfo(DataTable dt)  

确认。按年龄,描述和名称填充员工对象的代码在哪里?

答案 1 :(得分:1)

您只能使用标记为 PUBLIC 的DataBind属性。

您的Observable集合是内部的。

答案 2 :(得分:0)

您必须创建一个CollectionViewSource对象并将ObservableCollection分配给其source属性:

public CollectionViewSource datasource {get;set;}

...


datasource = new CollectionViewSource { Source = yourObservableCollection };
// you can do some sorting or grouping stuff here

你的Binding应该是这样的:

<DataGrid ItemsSource="{Binding Path=datasource.View}" x:Name="dtgrdemp"