我試圖使用表名從我的數據庫中檢索表的函數。 我得到它的工作使用一個DataTable,但我更喜歡使用一個ObservableCollection /列表,因爲我可以用它在爲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
不可能的。介紹您的用例,以便我們提供解決方案。 – Jon
您可以製作一個界面(IDisplayable)並讓不同的類實現它嗎?這將是更好的OO風格,然後只是使用對象。 – Daniel
@Jon:對不起,我沒有用例,只是我在紙上做了一些筆記,但沒有涉及到這些,我對它們的知識仍然太少,無法實際使用它們。 – Kryptoxx