2016-08-04 46 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); 
    } 
}