我正在尝试创建一个可以使用表名从我的数据库中检索表的函数。我已经使用 DataTable 让它工作,但我更喜欢使用 ObservableCollection/List,因为然后我可以在 ListCollectionView 中使用它,以便在 WPF 的 DataGrid 中使用它的分组可能性。
但是我现在面临的问题是我在 DataManager 类中创建的函数应该返回与表对应的不同类型的集合。我如何定义一个 ObservableCollection/List 类型在创建时定义?
示例函数(这不起作用,但可以解释我想要做什么):
...
public ObservableCollection<object> GetTable(string name)
{
ObservableCollection<object> table = null;
switch (name)
{
case "PriceList":
table = new ObservableCollection<PriceItem>();
//Business logic
break;
case "CustomerTable":
table = new ObservableCollection<Customer>();
//Business logic
break;
}
return table;
}
...
或者可能
...
public ObservableCollection<object> GetTable(string name)
{
ObservableCollection<object> table;
switch (name)
{
case "PriceList":
table = getPriceList();
break;
case "CustomerTable":
table = getCustomers();
break;
}
return table;
}
private ObservableCollection<PriceItem> getPriceList()
{
ObservableCollection<PriceItem> table = null;
//Bussiness logic
return table;
}
...
修改方法草案(我知道这可能是完全错误的):
public ObservableCollection<T> GetTable<T>()
{
ObservableCollection<T> table = new ObservableCollection<T>();
switch (typeof(T))
{
case "FarrisSeries":
table = new ObservableCollection<FarrisSeries>();
//Business logic
break;
case "FarrisSpecs":
table = new ObservableCollection<object>();
//Business logic
break;
}
return table;
}
可能的用例(我可能做错了,但我仍然尝试过:P)
Situation
---------
Window consists of MenuBar and a DataGrid.
In the menu there is a DropDownButton containing
a menu which contains a list of all table names.
Clicking any button will trigger a command that
will load the table into the DataGrid using the
MenuItem Header as a parameter. The command will
then load the appropriate ObservableCollection
(containing Objects of type related to table name)
into the DataGrid.
Case 1:
- User Clicks "PriceList"
- function LoadTable("PriceList") is called
- function retrieves PriceItems from the database
- function returns ObservableCollection<PriceItem>
- return is stored in the Object bound to the DataGrid
Case 2:
- User Clicks "Customer"
- function LoadTable("Customers") is called
- function retrieves Customers from the database
- function returns ObservableCollection<Customer>
- return is stored in the Object bound to the DataGrid