2012-06-15 208 views
8

嗨我正在嘗試將列表<>綁定到組合框。wpf組合框綁定

<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。

+0

你可以發佈'客戶'類嗎? –

+1

您是否確認List中實際上有東西是您Feeding到ItemsSource中的東西(在它被設置的時候,因爲您沒有此設置作爲綁定)? – Tim

回答

23

嘗試與實際綁定對象

XAML方法設置ItemsSource屬性(建議):

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

此外,在您的客戶屬性的setter應該引發PropertyChanged事件

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

如果上述不起作用,請嘗試將綁定部分從構造函數移動到OnLoaded覆蓋方法。頁面加載時,可能會重置您的值。

+1

好的我已經試過了。但是組合框是空的。我也在PageLoaded事件中嘗試過它。 – Veeesss

3

作爲Steve的回答擴展,

您需要設置您的窗體的datacontext。

目前你有這樣的:

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

應該改成這樣:

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

然後當史蒂夫注意到你需要在視圖模型的另一個屬性來存儲所選擇的項目。