无法将 observablecollection 绑定到 MVVM 中的数据网格
我对 MVVM 完全陌生。我试图将sqlserver中的数据绑定到WPF中的Datagrid并对其执行编辑、更新和删除操作。 现在,我无法至少使用 MVVM 中的可观察集合将数据从 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>
以下是我的“view”代码,其中我以人的身份参加了一个课程
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();
}
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"
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>
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);
}
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码
Empdata.Add(new EmpInfo(dt));
没有用任何内容填充可观察集合Empdata
!至少你的构造函数确认了这一点
。按年龄、描述和姓名填充员工对象的代码在哪里?
Your code
Empdata.Add(new EmpInfo(dt));
isn't populating the observable collectionEmpdata
with anything!Atleast thats what your constructor
confirms. Where is the code that populates the employee object by Age, Description and Name?
您只能对标记为PUBLIC 的数据绑定属性。
您的 Observable 集合是内部的。
You can only DataBind Properties that are marked as PUBLIC.
Your Observable collection is internal.
您必须创建一个 CollectionViewSource 对象并将 ObservableCollection 分配给其 source 属性:
您的 Binding 应该如下所示:
You have to create a CollectionViewSource object and assign your ObservableCollection to its source property :
your Binding should then look like: