c# - 在 UWP 应用中使用 SQL Server 数据库(名称在当前上下文中不存在)
问题描述
我正在尝试遵循此处找到的在 UWP 应用程序中使用 SQL Server 数据库教程:https ://docs.microsoft.com/en-us/windows/uwp/data-access/sql-server-databases
我已按照教程进行操作,但在同一个地方不断收到相同的错误。
我使用的是 Employee 表而不是教程中的 Products 表,但我已经尝试按照教程使用 te 产品表,但它会在相同的地方导致错误。
由于某种原因,它似乎无法从产品/员工类中引用 ObservableCollection 方法,并且无法绑定 xaml 文件中的属性。
Employee.cs 代替产品类:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinApp
{
public class Employee : INotifyPropertyChanged
{
public int EmployeeID { get; set; }
public string LastName { get; set; } = string.Empty;
public string FirstName { get; set; } = string.Empty;
public string Title { get; set; }
public string TitleOfCourtesy { get; set; }
public DateTime? BirthDate { get; set; }
public DateTime? HireDate { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string HomePhone { get; set; }
public string Extension { get; set; }
public byte[] Photo { get; set; }
public string Notes { get; set; }
public int ReportsTo { get; set; }
public string PhotoPath { get; set; }
public Employee Manager { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ObservableCollection<Employee> GetEmployees(string connectionString)
{
const string GetEmployeesQuery = "select * FROM Employee";
var employees = new ObservableCollection<Employee>();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetEmployeesQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var emp = new Employee();
emp.EmployeeID = reader.GetInt16(0);
emp.LastName = reader.GetString(1);
emp.FirstName = reader.GetString(2);
employees.Add(emp);
}
}
}
}
}
return employees;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
}
}
在MainPage.xaml.cs 发现错误,GetEmployees 在当前上下文中不存在:
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace WinApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
InventoryList.ItemsSource = GetEmployees((App.Current as App).ConnectionString);
}
}
}
MainPage.xaml 存在绑定错误的位置:
<Page
x:Class="WinApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WinApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid Background="{ThemeResource SystemControlAcrylicWindowBrush}">
<RelativePanel>
<ListView Name="InventoryList"
SelectionMode="Single"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.IsVerticalRailEnabled="True"
ScrollViewer.VerticalScrollMode="Enabled"
ScrollViewer.HorizontalScrollMode="Enabled"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.IsHorizontalRailEnabled="True"
Margin="20">
<ListView.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="ID" Margin="8,0" Width="50" Foreground="DarkRed" />
<TextBlock Text="Product description" Width="300" Foreground="DarkRed" />
<TextBlock Text="Packaging" Width="200" Foreground="DarkRed" />
<TextBlock Text="Price" Width="80" Foreground="DarkRed" />
<TextBlock Text="In stock" Width="80" Foreground="DarkRed" />
</StackPanel>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Employee">
<StackPanel Orientation="Horizontal" >
<TextBlock Name="ItemId"
Text="{x:Bind EmployeeID}"
Width="50" />
<TextBlock Name="ItemName"
Text="{x:Bind FirstName}"
Width="300" />
<TextBlock Text="{x:Bind LastName}"
Width="200" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</RelativePanel>
</Grid>
</Grid>
</Page>
解决方案
你的GetEmployees
方法是在Employee
类中定义的,不能直接在MainPage
类中使用。
尝试这个:
- 将方法修改
GetEmployees
为静态方法,以便类可以调用
public static ObservableCollection<Employee> GetEmployees(string connectionString)
{
//...
}
- 在调用前添加类名
InventoryList.ItemsSource = Employee.GetEmployees((App.Current as App).ConnectionString);
如果不添加对应的引用,对应的类型(如Employee
)会在代码编辑器中出现波浪线。将光标移动到波浪线处,会有一个小灯泡,点击后,可以引入对应的命名空间(这也适用于XAML)。
谢谢。
推荐阅读
- swift - FlatMapLatest 跳过触发器,直到最新的 observable 完成
- c# - 如何修复 Angular/.NET 项目中的“跨域请求被阻止:同源策略不允许读取远程资源”
- python - 如何在给定单词之前和之后查找文本并输出到不同的文本文件中?
- android - 如果图像为空,则打印消息
- python - 是否可以使用模板中的参数调用 python 函数?[姜戈]
- python - 如何使用 XPath 提取与给定模式不匹配的项目?
- linux - 删除具有低质量碱基调用的读取
- awk - 根据 csv 中的列值获取行
- javascript - 无论如何要在鼠标仍在移动区域时停止“onmousemove”功能?
- python - 当值是python中的列表时如何将值添加到字典中