c#从数据库中添加项目到组合框

时间:2014-04-26 15:55:58

标签: c# wpf linq combobox user-controls

我想用我的数据库中的项目填充一个组合框我做了这个:

 public partial class addAssoc : Window
{
    private libraryDBEntities1 context;
    public addAssoc()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        context = new libraryDBEntities1();
        System.Windows.Data.CollectionViewSource libraryDBEntities1ViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("libraryDBEntities1ViewSource")));
        // Load data by setting the CollectionViewSource.Source property:
        // libraryDBEntities1ViewSource.Source = [generic data source]

        var q = from b in context.textbooks
                select b.Title;


        foreach(var item in q){
            titleComboBox.Items.Add(item);

        }
    }
}
}

它似乎部分工作,我能够将鼠标悬停在组合框中的项目上,并且它们会突出显示,但它们没有文本。这是什么原因?任何帮助将不胜感激。我正在使用wpf

 <ComboBox x:Name="titleComboBox" Width="120" VerticalAlignment="Center" Grid.Row="0" Margin="3" ItemsSource="{Binding}" Height="Auto" HorizontalAlignment="Left" DisplayMemberPath="Title" Grid.Column="1">

1 个答案:

答案 0 :(得分:0)

添加

ItemsSource={Binding}

您告诉ComboBox将其DataContext用作ItemsSource。

删除此内容然后重试。此外,我建议您阅读data binding

修改:同时删除

DisplayMemberPath='Title'