wpf combobox binding

前端 未结 2 1041
青春惊慌失措
青春惊慌失措 2020-12-16 23:54

Hi I´m trying to bind a List<> to a combobox.



public OfferEdi         


        
相关标签:
2条回答
  • 2020-12-17 00:05

    Try setting the ItemsSource property with an actual Binding object

    XAML Method (recommended):

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

    Programmatic method:

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

    Also, the setter on your Customer property should raise the PropertyChanged event

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

    If the above does not work, try moving the binding portion from the constructor to the OnLoaded override method. When the page loads, it may be resetting your values.

    0 讨论(0)
  • 2020-12-17 00:21

    As an expansion on Steve's answer,

    You need to set the datacontext of your form.

    Currently you have this:

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

    It should be changed to this:

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

    Then as Steve noted you will need another property on the viewmodel to store the selected item.

    0 讨论(0)
提交回复
热议问题