【发布时间】:2011-11-17 09:14:19
【问题描述】:
对于 Caliburn.Micro,我想知道将 EF4 实体作为 ViewModel 的属性公开的利弊(讨论的一种技术hereand here)。这使我可以避免为每个字段编写 getter 和 setter(参见下面的 OneCustomer)。缺点是我需要在 XAML 中编写所有绑定语句(下面的 LastName 不在 ViewModel 中,但确实需要 XAML 绑定)。如果我坚持使用每个字段的属性(如下面的 FirstName)填充 ViewModel 的规定技术,我最终将不得不编写大量额外的代码,以便调用 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" />
提前致谢。
【问题讨论】:
标签: wpf entity-framework mvvm caliburn.micro