8

嗨,我正在尝试将 List<> 绑定到组合框。

<ComboBox Margin="131,242,275,33" x:Name="customer" Width="194" Height="25"/>

public OfferEditPage()
    {
        InitializeComponent();
        cusmo = new CustomerViewModel();
        DataContext = this;
        Cusco = cusmo.Customer.ToList<Customer>();
        customer.ItemsSource = Cusco;
        customer.DisplayMemberPath = "name";
        customer.SelectedValuePath = "customerID";
        customer.SelectedValue = "1";
    }

我没有错误,但组合框总是空的。库斯科是我名单的财产。我不知道这段代码有什么问题。你能帮助我吗?

问候

 public class Customer
{
    public int customerID { get; set; }
    public string name { get; set; }
    public string surname { get; set; }
    public string telnr { get; set; }
    public string email { get; set; }
    public string adress { get; set; }
}

这是我的模型的客户类。

public class CustomerViewModel
{
    private ObservableCollection<Customer> _customer;

    public ObservableCollection<Customer> Customer
    {
        get { return _customer; }
        set { _customer = value; }
    }

    public CustomerViewModel()
    {
        GetCustomerCollection();
    }

    private void GetCustomerCollection()
    {
        Customer = new ObservableCollection<Customer>(BusinessLayer.getCustomerDataSet());
    }

}

这就是 ViewModel。

4

2 回答 2

23

尝试使用实际的 Binding 对象设置 ItemsSource 属性

XAML 方法(推荐):

<ComboBox
    ItemsSource="{Binding Customer}"
    SelectedValue="{Binding someViewModelProperty}"
    DisplayMemberPath="name"
    SelectedValuePath="customerID"/>

程序化方法:

Binding myBinding = new Binding("Name");
myBinding.Source = cusmo.Customer; // data source from your example

customer.DisplayMemberPath = "name";
customer.SelectedValuePath = "customerID";
customer.SetBinding(ComboBox.ItemsSourceProperty, myBinding);

此外,您的 Customer 属性上的设置器应该引发 PropertyChanged 事件

public ObservableCollection<Customer> Customer
{
    get { return _customer; }
    set
    {
        _customer = value;
        RaisePropertyChanged("Customer");
    }
}

如果上述方法不起作用,请尝试将绑定部分从构造函数移至 OnLoaded 覆盖方法。当页面加载时,它可能会重置您的值。

于 2012-06-15T18:35:38.290 回答
3

作为史蒂夫答案的扩展,

您需要设置表单的数据上下文。

目前你有这个:

InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;

应该改成这样:

InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = cusmo;

然后正如史蒂夫指出的那样,您将需要视图模型上的另一个属性来存储所选项目。

于 2012-06-27T14:55:35.103 回答