使用Caliburn.Micro,我想了解将EF4实体公开为ViewModel属性的优缺点(这是在这里和这里讨论的一种技术)。这样可以避免为每个字段编写getter和setter(请参见下面的OneCustomer)。缺点是我需要在XAML中编写所有绑定语句(下面的LastName不在ViewModel中,但确实需要XAML绑定)。如果我坚持使用为每个字段填充ViewModel属性的预定技术(如下面的FirstName),最终我将不得不编写大量额外的代码,以便调用NotifyOfProperyChange。该应用程序将非常庞大。我应该将每个实体公开为ViewModel属性吗?
在我的ViewModel中:
private MyEntities _context = new MyEntities();
private BindableCollection<Customer> _custBindableCollection;
private Customer _oneCustomer;
private string _firstName;
public void Load()
{
_custBindableCollection = new BindableCollection<Customer>(_context.Customers.Where(row => row.CustomerType == "FOO"));
AllCustomers = _custBindableCollection;
_oneCustomer = _custBindableCollection.FirstOrDefault();
FirstName = _oneCustomer.FirstName;
OneCustomer = _oneCustomer;
}
public BindableCollection<Customer> AllCustomers
{
get { return _custBindableCollection;}
set {_custBindableCollection = value;
NotifyOfPropertyChange(() => AllCustomers);}
}
public Customer OneCustomer
{
get { return _oneCustomer;}
set { _oneCustomer = value;
NotifyOfPropertyChange(() => OneCustomer);}
}
public string FirstName
{
get { return _firstName; }
set {
_firstName = value;
_oneCustomer.FirstName = value;
NotifyOfPropertyChange(() => FirstName);
NotifyOfPropertyChange(() => CanSaveChanges);
}
}
public void SaveChanges()
{ _context.SaveChanges(); }
public bool CanSaveChanges { get { return IsValid; } }
我的观点:
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="First Name:" />
<TextBox x:Name="FirstName" />
</StackPanel>
<StackPanel Orientation="Horizontal" DataContext="{Binding Path=OneCustomer}">
<Label Content="Last Name:" />
<TextBox x:Name="LastName" Text="{Binding LastName}" />
</StackPanel>
<Button Content="Load Data" x:Name="Load" />
<Button Content="Save" x:Name="SaveChanges" />
<DataGrid x:Name="AllCustomers" />
谢谢您的提前帮助。