C# WPF-将数据从DAL传递到UI
这里是新手,所以请放松 我有一个WPF项目正在进行中,我已经创建了一个数据访问层,我通过以下代码获得了所需的数据:C# WPF-将数据从DAL传递到UI,c#,wpf,mvvm,C#,Wpf,Mvvm,这里是新手,所以请放松 我有一个WPF项目正在进行中,我已经创建了一个数据访问层,我通过以下代码获得了所需的数据: public static List<Model.CountryList> GetAllCountriesList() { SqlConnection connection = new DatabaseConnection().ConnectToBooze(); SqlCommand cmd = new SqlCommand()
public static List<Model.CountryList> GetAllCountriesList()
{
SqlConnection connection = new DatabaseConnection().ConnectToBooze();
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = "dbo.spGetAllCountries";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
connection.Open();
reader = cmd.ExecuteReader();
var CompanyList = new List<Model.CountryList>();
while (reader.Read())
{
while (reader.Read())
{
var Cli = new Model.CountryList();
Cli.CountryID = Convert.ToInt32(reader["CountryID"]);
Cli.CountryName = reader["CountryName"].ToString();
//Add the country to Country List
CompanyList.Add(Cli);
}
}
//Return list
return CompanyList;
}
public静态列表GetAllCountriesList()
{
SqlConnection=newdatabaseconnection().ConnectToBooze();
SqlCommand cmd=新的SqlCommand();
SqlDataReader;
SqlDataAdapter da=新的SqlDataAdapter();
cmd.CommandText=“dbo.spGetAllCountries”;
cmd.CommandType=CommandType.storedProcess;
cmd.Connection=连接;
connection.Open();
reader=cmd.ExecuteReader();
var CompanyList=新列表();
while(reader.Read())
{
while(reader.Read())
{
var Cli=new Model.CountryList();
Cli.CountryID=Convert.ToInt32(读卡器[“CountryID]”);
Cli.CountryName=reader[“CountryName”].ToString();
//将国家/地区添加到国家/地区列表
公司列表添加(Cli);
}
}
//返回列表
返回公司列表;
}
我正在努力解决的是,如何将DAL传递到我的表示层?我的想法是在表示层上创建一个“Data”类,该类从DAL调用上述方法并返回此列表,但是,我不确定如何在没有“cannot implicitly convert type list to list”错误的情况下执行此操作,我尝试的是:
public static List<Model.CountryList> GetAllCountries()
{
return DataAccessLayer.DatabaseGets.GetAllCountriesList();
}
公共静态列表GetAllCountries()
{
返回DataAccessLayer.DatabaseGets.GetAllCountriesList();
}
感谢您的指导。MVVM只是一种分离关注点和IMHO的方法,它是一个荣耀的三层数据系统 如何将其从DAL传递到表示层 将数据放置/读取到MVVM的
VM
中,并从视图中使用数据,该视图将通过INotifyPropertyChange
从VM(均在后台)加载任何内容时,在视图上通过绑定控件发出通知
请参阅我在MVVM上的博客文章,以帮助您入门:通过我的阅读,您询问的关于体系结构的问题比任何错误都多。考虑到这一点,我认为您提供的代码实际上是某个存储库的一部分,该存储库将在其他地方实现您定义的接口,并将其注入任何需要该功能的viewmodel中 简化的层图可以是:
UI -> ViewModel -> Model <- DAL
namespace MyApp.Model
{
public interface IMyRepo
{
IEnumerable<Model.CountryList> GetAllCountries();
}
}
namespace MyApp.DAL
{
public class MyRepo : IMyRepo
{
IEnumerable<Model.CountryList> GetAllCountries()
{
/**
data access
**/
}
}
}
namespace MyApp.ViewModel
{
public class MainViewModel : ViewModelBase
{
public MainViewModel(IMyRepo repo)
{
this.Repo = repo;
}
}
}
UI->ViewModel->Model您提供的任何代码在我看来都是可以的。你能更具体地说明你看到了什么错误吗。也许是整个错误?好吧,我是个白痴。我在表示层中使用了不同的模型,因此出现了错误。现在通过完全引用DAL中的模型解决了此问题。谢谢你的帮助。在发布答案后立即看到你的评论,很高兴你找到了答案!由于您基本上是在MVVM中讨论模型-视图-模型通信,我发现以下搜索非常有用: