我试图从数据库表绑定数据到我的 ComboBox . 我按照本教程http://blog.cylewitruk.com/2010/09/wpf-combobox-and-databinding-datacontext-itemssource-displaymemberpath-selecteditem-selectedvalue-selectedvaluepath/但他只通过手动添加数据来绑定数据 .

当我尝试添加从数据库中获取数据的方法时,我的Window.DataContext将给出以下错误:

对象引用未设置为对象的实例 .

我应该在哪里添加代码来填充我的 ComboBox

这是我的xaml文件 .

<Window 
x:Name="windowMain" 
x:Class="QSMSystemView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Quickserve Marketing Inventory and Accouting System" Height="437" Width="499"
xmlns:ViewModels="clr-namespace:QSMSystemView">

<Window.DataContext>
    <ViewModels:ProductViewModel />
</Window.DataContext>
...

<ComboBox x:Name="comboBoxSupplier" 
          ItemsSource="{Binding Suppliers, Mode=OneWay}"
          DisplayMemberPath="Name"
          SelectedValue="{Binding SelectedProductSupplier}"
          SelectedValuePath="ID"
          />

这是我的viewmodel:

public class ProductViewModel : ViewModel
{

    private SuppliersModel suppliersModel;

    public ObservableCollection<Supplier> Suppliers { get; set; }

    private Int16 selectedProductSupplier;

    public Int16 SelectedProductSupplier
    {
        get { return this.selectedProductSupplier; }
        set
        {
            this.selectedProductSupplier = value;

            this.NotifyPropertyChanged("SelectedProductSupplier");
        }
    }

    public ProductViewModel()
    {
        this.Suppliers = new ObservableCollection<Supplier>();
        this.suppliersModel = new SuppliersModel();
        this.GetSuppliersFromDatabase();
    }

    public void GetSuppliersFromDatabase()
    {
        foreach (Supplier supplier in suppliersModel.All())
        {
            Console.WriteLine("Id: " + supplier.ID);
            Console.WriteLine("name: " + supplier.Name);
            this.Suppliers.Add(supplier);
        }
    }

}

这是我的供应商类 .

public class Supplier
{
    public Int16 ID { get; set; }
    public String Name { get; set; }

    public Supplier(Int16 id, String name)
    {
        this.ID = id;
        this.Name = name;
    }
}

注意:如果我不尝试从数据库中获取数据,只需通过以下方式手动填充供应商:this.Supplier.Add(new Supplier(1,“foo”);那么我的代码将运行且没有错误 .