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 1527
佛祖请我去吃肉
佛祖请我去吃肉 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<CUSTOMER> _customers = new ObservableCollection<CUSTOMER>();
        public IList<CUSTOMER> 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:

    <ComboBox ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}">
        ...
    </ComboBox>
    

    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"));
    
    0 讨论(0)
  • 2021-01-24 06:07

    You could cast the SelectedItem property of the ComboBox to a CUSTOMER object to get the currently selected item:

    CUSTOMER selectedCustomer = C1.SelectedItem as CUSTOMER;
    if(selectedCustomer != null)
        MessageBox.Show(selectedCustomer.CUSTOMER_NAME);
    

    To select an item you set the SelectedItem property to a CUSTOMER object that is included in the ComboBox's ItemsSource:

    C1.SelectedItem = C1.Items[0]; //selects the first customer (index = 0)
    

    Or if you know the name or description of the customer:

    string theName = "some customer name...";
    C1.SelectedItem = C1.Items.OfType<CUSTOMER>().FirstOrDefault(x => x.CUSTOMER_NAME == theName);
    
    0 讨论(0)
提交回复
热议问题