我只是在玩 MVVM Light,我想我已经了解了它,但我有一个问题。
我正在使用 SQL Server CE 工具箱,它为我的数据库 (SQLCE) 生成类、映射等。其中一个表称为 Profile,我想将其用作我也可以绑定(bind)的属性。这是我的 ViewModel 代码
public class ProfileViewModel : ViewModelBase
{
private Profile profile; // Profile is the class created by SQLCE Toolbox for table mapping
public Profile UserProfile
{
get { return profile; }
set
{
profile = value;
RaisePropertyChanged("UserProfile");
}
}
public ProfileViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
UserProfile = new Profile()
{
Name = "NA",
Age = 22
}
}
else
{
// Code runs "for real"
UserProfile = GetProfile();
}
}
}
在表达式混合中,我可以看到 ViewModel,但看不到 Profile 属性,因此我猜测某处正在生成异常。
我确实尝试将混合作为一个过程附加,但没有出现错误。经过一番阅读后,我发现 Blend 无法连接到数据库,因此您必须在 DesignMode 下弥补一些数据。我尝试只执行 UserProfile = new Profile()
但我猜测它仍在尝试使用数据库来创建它?
编辑: 好的,我遇到的问题与使用 SQLCE 有关。如果我尝试使用 WPF 和 MS SQL 进行类似的操作,那么一切都会正常工作。
编辑2: 这肯定和数据库有关。如果我从上面的代码中删除公共(public)属性 UserProfile,则可以从 Blend 中看到所有其他属性(未在我的代码中显示)。如果我把它加回来,那么没有一个是可见的。那么我怎样才能使它可混合呢?
最佳答案
您必须使用定位器
机制。默认情况下,您可以在 MVVM 应用程序中看到它。
在设计模式下,您将提供 Profile
对象的预构建版本,但在非设计模式下,Profile
对象将通过你的数据库。因此,您不会直接使用 new Profile()
,而是使用类似于 Locator.ProvideMeWithUserProfile()
的内容。
您可以查看this video例如实现它的方法。
关于c# - MVVM Light 和 SQL Server CE 在 View 模型中生成代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15074827/