将combobox绑定到linq2sql时出现WPF异常

时间:2016-08-04 10:30:54

标签: c# wpf linq-to-sql combobox binding

我有一个ComboBox:

 <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);
        }
    }

我得到例外(在最后一行)说:&#39;指定演员表无效。&#39;

请帮我解决这个问题!

1 个答案:

答案 0 :(得分: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);
    }
}
相关问题