我正在使用MVVm工具包在WPF中编写应用程序,并且存在连接视图模型和视图的问题。如何设置用户控件的数据环境
该模型使用ado.net实体框架创建。
视图模型:
public class CustomerViewModel
{
private Models.Customer customer;
//constructor
private ObservableCollection<Models.Customer> _customer = new ObservableCollection<Models.Customer>();
public ObservableCollection<Models.Customer> AllCustomers
{
get { return _customer; }
}
private Models.Customer _selectedItem;
public Models.Customer SelectedItem
{
get { return _selectedItem; }
}
public void LoadCustomers()
{
List<Models.Customer> list = DataAccessLayer.getcustomers();
foreach (Models.Customer customer in list)
{
this._customer.Add(customer);
}
}
}
和视图(在此刻后面没有代码):
<UserControl x:Class="Customers.Customer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
xmlns:vm ="clr-namespace:Customers.ViewModels"
d:DesignHeight="300" d:DesignWidth="300"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" >
<Grid>
<toolkit:DataGrid ItemsSource="{Binding AllCustomers}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AutoGenerateColumns="True">
</toolkit:DataGrid>
<toolkit:DataGrid ItemsSource="{Binding SelectedItem.Orders}">
</toolkit:DataGrid>
</Grid>
</UserControl>
而且dataaccesslayer类:
class DataAccessLayer
{
public List<Customer> customers = new List<Customer>();
public static List<Customer> getcustomers()
{
entities db = new entities();
var customers = from c in db.Customer.Include("Orders")
select c;
return customers.ToList();
}
}
的问题是,没有数据仅仅因为没有设置数据上下文而显示。我试图在代码隐藏方面做到这一点,但没有奏效。无论如何,我宁愿在xaml文件中执行它。另一个问题是SelectedItem绑定 - 从不使用代码。
在您的代码中,您的View Model上有AllCustomers属性,但您绑定了Customers。 – mak 2010-05-17 17:58:35
我正在稍微清理代码并发出错字。工作代码中的绑定当然是正确的。 – EVA 2010-05-17 18:17:06