2013-05-30 65 views
0

我試圖使用表名從我的數據庫中檢索表的函數。 我得到它的工作使用一個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 
+0

不可能的。介紹您的用例,以便我們提供解決方案。 – Jon

+0

您可以製作一個界面(IDisplayable)並讓不同的類實現它嗎?這將是更好的OO風格,然後只是使用對象。 – Daniel

+0

@Jon:對不起,我沒有用例,只是我在紙上做了一些筆記,但沒有涉及到這些,我對它們的知識仍然太少,無法實際使用它們。 – Kryptoxx

回答

4

兩個選項涌現在腦海裏:

  • 返回非泛型IList類型,而不是ObservableCollection<>。我期望綁定仍然可以解決,實際的類型是ObservableCollection<>並且能夠觀察到更改。
  • 使該方法一般,並且擺脫了名稱參數的完全:制定出基於集合的類型參數來獲取。 (這感覺有點醜對我來說,因爲它不會真正通用的,在所有的可能性 - 你有一組有限的類型,你可以使用。)
+0

好吧,我設法使這個方法是通用的(我從來沒有參與面向對象編程的這部分),但我不明白你的意思是獲取類型參數。我嘗試過typeof(T),但似乎不起作用(上面添加了代碼)。然而,這些新東西讓我看到了新的可能性,所以如果我取得更多進展,我會繼續嘗試並在這裏發佈。儘管非常感謝您的快速回答! :) – Kryptoxx

+0

@TomVandenbussche爲什麼不去第一個選項。只需將您的方法的返回類型更改爲「IList」或「ICollection」即可完成。 – Clemens

+0

哦,哇,我真的不明白你是什麼意思的非通用IList(和VS並沒有給我太多的信息),但現在我發現它是什麼,我的作品完美!非常感謝!! – Kryptoxx

1

我試圖做一個函數,可以使用表名從我的 數據庫檢索表。我得到它的工作使用一個DataTable, 但我更喜歡使用一個ObservableCollection /列表,因爲我 可以使用它在爲ListCollectionView使用它的分組也將在WPF DataGrid中 可能性。

回答這個我已經創建了一個樣本。一探究竟。我正在使用Northwind db。這爲DataGrid提供了客戶可數據加載並實時分組。

使用這個,你可以根據數據庫中的表名簡單地調用你的表,然後把這個表結果作爲itemsource傳遞給Datagrid,以獲得它的分組已經創建了一個文本框,你可以在其中提供分組名。在丟失的焦點上,分組會反映在Datagrid上。試試這個,如果你有任何疑問讓我知道。

<Window x:Class="TempTest.DataTableTest" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="DataTableTest" 
     Width="548" 
     Height="292"> 
    <Window.Resources> 
     <Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}"> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="{x:Type GroupItem}"> 
         <Expander x:Name="exp" 
            Background="White" 
            Foreground="Black" 
            IsExpanded="True"> 
          <Expander.Header> 
           <TextBlock Text="{Binding Job Title}" /> 
          </Expander.Header> 
          <ItemsPresenter /> 
         </Expander> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Window.Resources> 

    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="50" /> 
      <RowDefinition Height="210*" /> 
     </Grid.RowDefinitions> 
     <DataGrid Name="dataGrid1" 
        Grid.Row="1" 
        AutoGenerateColumns="true"> 
      <DataGrid.GroupStyle> 
       <GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}"> 
        <GroupStyle.Panel> 
         <ItemsPanelTemplate> 
          <DataGridRowsPresenter /> 
         </ItemsPanelTemplate> 
        </GroupStyle.Panel> 
       </GroupStyle> 
      </DataGrid.GroupStyle> 
     </DataGrid> 
     <Button Name="button1" 
       Width="56" 
       Height="25" 
       Margin="458,9,0,0" 
       HorizontalAlignment="Left" 
       VerticalAlignment="Top" 
       Click="button1_Click" 
       Content="Button" /> 
     <TextBox Name="textBox1" 
       Width="123" 
       Height="24" 
       Margin="18,10,0,0" 
       HorizontalAlignment="Left" 
       VerticalAlignment="Top" /> 
     <TextBox Name="textBox2" 
       Width="123" 
       Height="24" 
       Margin="147,10,0,0" 
       HorizontalAlignment="Left" 
       VerticalAlignment="Top" /> 
    </Grid> 
</Window> 

此代碼背後。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Shapes; 
using System.Data; 
using System.ComponentModel; 

namespace TempTest 
{ 
    /// <summary> 
    /// Interaction logic for DataTableTest.xaml 
    /// </summary> 
    public partial class DataTableTest : Window 
    { 
     public DataTableTest() 
     { 
      InitializeComponent(); 
      textBox2.LostFocus += new RoutedEventHandler(textBox2_LostFocus); 
     } 

     void textBox2_LostFocus(object sender, RoutedEventArgs e) 
     { 
      if (!string.IsNullOrWhiteSpace(textBox2.Text)) 
      { 
       var cv = dataGrid1.ItemsSource as CollectionView; 
       if (cv != null) 
       { 
        cv.GroupDescriptions.Clear(); 
        cv.GroupDescriptions.Add(new PropertyGroupDescription(textBox2.Text)); 
       } 

      } 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 

      DataTable dt = new DataTable(); 


      if (textBox1.Text.Equals("customers", StringComparison.InvariantCultureIgnoreCase)) 
      { 
       Data.Northwind_2007DataSetTableAdapters.CustomersTableAdapter c = new Data.Northwind_2007DataSetTableAdapters.CustomersTableAdapter(); 
       dt = c.GetData(); 
      } 
      else if (textBox1.Text.Equals("employees", StringComparison.InvariantCultureIgnoreCase)) 
      { 
       Data.Northwind_2007DataSetTableAdapters.EmployeesTableAdapter emp = new Data.Northwind_2007DataSetTableAdapters.EmployeesTableAdapter(); 
       dt = emp.GetData(); 
      } 


      dataGrid1.ItemsSource = (CollectionView)CollectionViewSource.GetDefaultView(dt.DefaultView); 

     } 
    } 
} 
+0

感謝您的回答,但由於我在MVVM模式下工作,所以這不是我正在尋找的內容。 – Kryptoxx

+0

您可以參考MVVM中使用的代碼。 – JSJ

+0

我知道,但畢竟有關ObservableCollections和泛型與非泛型IList學習的訣竅,我留在那些類而不是DataTable類。雖然您的幫助非常感謝! – Kryptoxx