使用 Caliburn.Micro,我想知道将 EF4 实体公开为 ViewModel 的属性(讨论过的一种技术)的优缺点here http://kboek.blogspot.com/2011/01/activerecord-caliburn-micro-and-one.html and here http://www.lhotka.net/weblog/InitialThoughtsOnMVVM.aspx)。这使我可以避免为每个字段编写 getter 和 setter(请参阅下面的 OneCustomer)。缺点是我需要在 XAML 中编写所有绑定语句(下面的 LastName 不在 ViewModel 中,但确实需要 XAML 绑定)。如果我坚持使用每个字段的属性填充 ViewModel 的规定技术(如下面的 FirstName),我最终将不得不编写大量额外的代码,以便调用 NotifyOfProperyChange。该应用程序将相当大。我应该将每个实体公开为 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" />
提前致谢。
使用 Caliburn.Micro 我想知道暴露的优点和缺点
EF4 实体作为 ViewModel 的属性(此处讨论的技术
和这里)。
我不确定优点/缺点,但我可以告诉你这两种方法都被使用。例如,以一个简单的登录屏幕为例,通常我将 UserName 放在 ViewModel 上的一个属性,但在表单更复杂的情况下,ViewModel 可以聚合其他 ViewModel(显示模型)来完成相同的事情。 CM 不会影响优缺点,更多的是关于 MVVM 的优缺点是什么。 CM 将帮助您绑定两者。
- 如果 ViewModel 上有一个名为 CustomerName 的属性,只需命名
文本框 x:name="CustomerName"。
- 如果 ViewModel 上有一个属于类实例的属性
名为 Customer,将文本框命名为 x:name="Customer_Name" 并再次命名为 CM
将处理绑定。
所以从上面的 xaml 来看:
<TextBox x:Name="LastName" Text="{Binding LastName}" />
您不需要在 StackPanel 上设置 DataContext。反而:
<TextBox x:Name="OneCustomer_LastName"/>
可以更轻松地绑定到 DataForms 和 DataGrid 的一件事是遵循一种方法,为数据在屏幕上的表示方式创建显示模型。
这是我的观点,但我个人永远不会直接绑定到 EF/Linq 实体。相反,我将创建一个显示模型来表示该实体以及我希望它如何显示和使用自动映射器 http://automapper.org/进行映射。在很多情况下,它是一对一的映射。这可能看起来是浪费时间,但它具有优势,特别是对于更复杂的数据模型布局,显示模型允许您展平数据以用于显示目的,并属性属性以进行验证,而无需将它们粘贴在数据模型实体上。有关更多信息,请参阅其中的章节ASP.NET MVC 实际应用 http://www.manning.com/palermo2/ book.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)