2016-08-04 74 views
1

我有一個組合框:WPF例外,同時結合組合框LINQ2SQL

<ComboBox Name="cmbSuppliers" ItemsSource="{Binding}" Grid.Column="1" Grid.Row="0" Height="30"></ComboBox> 

當試圖將它綁定在這個方法:

public void BindSuppliers() 
    { 
     using (ScanFlowDataClassesDataContext db = new ScanFlowDataClassesDataContext(GlobalConfig.connectionString)) 
     { 
      var suppliers = from s in db.Suppliers 
         select new 
         { 
          Id = s.Id, 
          Name = s.Name, 
         }; 
      cmbSuppliers.DisplayMemberPath = "Name"; 
      cmbSuppliers.SelectedValuePath = "Id"; 
      cmbSuppliers.ItemsSource = db.Suppliers.Select(s => s).OrderBy(s => s.Name); 
     } 
    } 

我得到異常(最後一行)說:「指定的轉換無效。'

請幫我解決這個問題!

+1

'的ItemsSource = 「{結合}」'在XAML似乎是多餘的,當你以後在代碼中設置ItemsSource屬性後面。除此之外,'db.Suppliers.Select(s => s)'似乎沒有意義。你可能只是想寫'cmbSuppliers.ItemsSource = suppliers.OrderBy(s => s.Name);'? – Clemens

+0

假設db對象是EntityFramework的datacontext對象。總是從EntityFrameWork的數據庫上下文將返回IQueryable。所以你把它轉換成List這樣cmbSuppliers.ItemsSource = db.Suppliers.OrderBy(s => s.Name).ToList(); –

回答

0

你可以嘗試這樣的事:

<ComboBox Name="cmbSuppliers" Grid.Column="1" Grid.Row="0" Height="30"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Item2} /> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

方法:

public void BindSuppliers() 
    { 
     using (ScanFlowDataClassesDataContext db = new ScanFlowDataClassesDataContext(GlobalConfig.connectionString)) 
    { 
     var suppliers = from s in db.Suppliers 
      select new Tuple<int,string>(s.Id, s.Name); 
     cmbSuppliers.DisplayMemberPath = "Item2"; 
     cmbSuppliers.SelectedValuePath = "Item1"; 
     cmbSuppliers.ItemsSource = suppliers.OrderBy(s => s.Item2); 
    } 
}