This my Xaml code for combo box with data binding :
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"));