Dev*_*Dan 5 wpf entity-framework mvvm caliburn.micro
使用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; } }
Run Code Online (Sandbox Code Playgroud)
在我看来:
<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" />
Run Code Online (Sandbox Code Playgroud)
提前致谢.
使用Caliburn.Micro,我想知道将EF4实体暴露为ViewModel的属性(这里和此处讨论的一种技术)的优缺点.
我不确定利弊,但我可以告诉你两种方法都使用了.例如,使用一个简单的登录屏幕,通常我将UserName放在ViewModel上,但是在表单更复杂的情况下,ViewModel可以聚合其他ViewModel(显示模型)来完成同样的事情.CM不会影响利弊,因为它更像是MVVM的问题,有哪些优点/缺点.CM将帮助您绑定到两者.
所以从上面的xaml:
<TextBox x:Name="LastName" Text="{Binding LastName}" />
Run Code Online (Sandbox Code Playgroud)
您不需要在StackPanel上设置DataContext.代替:
<TextBox x:Name="OneCustomer_LastName"/>
Run Code Online (Sandbox Code Playgroud)
可以更容易地绑定到DataForms和DataGrids的一件事是遵循一种方法,在该方法中,您可以为屏幕上的数据表示方式创建显示模型.
这是我的观点,但我个人永远不会直接绑定到EF/Linq实体.相反,我将创建一个显示模型来表示该实体以及我希望它如何显示,并使用AutoMapper来执行映射.在很多情况下,它是一对一的映射.这似乎是浪费时间,但它具有优势,特别是对于更复杂的数据模型布局,显示模型允许您展平数据以用于显示目的,并将属性归因于验证而不将其粘贴在数据模型实体上.有关详细信息,请查看ASP.NET MVC in Action一书中的相关章节.
| 归档时间: |
|
| 查看次数: |
2160 次 |
| 最近记录: |