0

我正在尝试将数据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"
          />

这是我的视图模型:

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"); 那么我的代码将毫无错误地运行。

4

0 回答 0