WPF ComboBox 数据绑定

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

我没有收到错误提示,但是下拉框一直是空的。 Cusco是我的列表属性。 我不知道这段代码哪里出了问题。 你能帮我吗?

问候

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

这是我的模型——Customer类。

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。


你能发布Customer类吗? - Carson Myers
1
你确定在将List作为ItemsSource传递给它时,列表中实际上有内容吗?(因为你没有将其设置为绑定) - Tim
2个回答

23
尝试使用实际的绑定对象设置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属性的setter应该引发PropertyChanged事件。

public ObservableCollection<Customer> Customer
{
    get { return _customer; }
    set
    {
        _customer = value;
        RaisePropertyChanged("Customer");
    }
}
如果上述方法不起作用,尝试将绑定部分从构造函数移动到OnLoaded重写方法中。当页面加载时,可能会重置您的值。

1
好的,我已经尝试过了。但是下拉框是空的。我还在PageLoaded事件中试过了。 - Veeesss

3
作为对Steve答案的扩展,
您需要设置表单的数据上下文。
目前您有以下内容:
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;

应该将其更改为以下内容:
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = cusmo;

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接