有人能告诉我为什么我从这段代码中得到"当前上下文中不存在‘车辆’名称"吗?它在最后一行,我试图连接一个字符串作为页眉。请注意,我是c#的新手,Windows应用商店的新手,SQLite的新手,也许更多。我不明白,如果我只是查询数据库并分配值来构造"Vehicle",为什么它在下一个语句中不识别它?
public MainPrintPage()
{
this.InitializeComponent();
MaintenancesViewModel = new maintenancesViewModel();
Maintenances = MaintenancesViewModel.GetMaintenances(App.CurrentVehicleId);
MaintenancesViewSource2.Source = Maintenances;
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<vehicles>().Where(
p1 => p1.VehID == App.CurrentVehicleId).SingleOrDefault();
var Vehicle = new vehicleViewModel();
Vehicle.VehID = query.VehID;
Vehicle.VehYear = query.VehYear;
Vehicle.VehMake = query.VehMake;
Vehicle.VehModel = query.VehModel;
}
string PageTitle = string.Format("{0} Maintenance Records", Vehicle.VehYear + " " + Vehicle.VehMake + " " + Vehicle.VehModel);
}
Vehicle
是在using
语句中声明的,它在最后一行超出了范围。尝试在using
语句之前声明Vehicle
。
在using
范围外声明变量并在其中赋值。你必须给它赋值,比如null或new,否则你会得到一个"未初始化"的错误。
vehicleViewModel Vehicle = null;
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
...
Vehicle = new vehicleViewModel();
...
}
附带说明一下,您的命名约定与绝大多数C#程序员所使用的相反。相反,类名的第一个字母应该是大写,局部变量应该是小写,如下所示:
VehicleViewModel vehicle = null;
vehicle = new VehicleViewModel();