I have created a combo box with data binding in WPF. I am not sure how to get value and set value of “comboboxselecteditem”

前端 未结 2 1529
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-24 05:49

This my Xaml code for combo box with data binding :

        

        
2条回答
  •  不知归路
    2021-01-24 06:06

    You can get and set the ComboBox's SelectedItem by binding to it, just as you bound the items of the ComboBox.

    It is a good practice to put the data members for your UI into a separate class. This is typically done in a view model using the MVVM (Model, View, View Model) paradigm.

    Something like this:

    class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection _customers = new ObservableCollection();
        public IList Customers
        {
            get { return _customers; }
        }
    
        private CUSTOMER _selectedCustomer = null;
        public CUSTOMER SelectedCustomer
        {
            get { return _selectedCustomer; }
            set
            {
                _selectedCustomer = value;
                OnPropertyChanged("SelectedCustomer");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void OnPropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
    

    And in your window class:

    class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
    
            DataContext = new ViewModel();
        }
    }
    

    And finally in your XAML:

    
        ...
    
    

    I would also move the code that loads the customers from the database into the ViewModel, and once done set the SelectedCustomer property to a reasonable default. For example, to select the customer whose name is Bob, run the following once the objects have been loaded from the database:

    SelectedCustomer = _customers.FirstOrDefault(customer => customer.CUSTOMER_NAME.Equals("Bob"));
    

提交回复
热议问题