I have a combo box that I bind to an observable collection, which gets changed (according to company selected) and a large number of companies will have a single account (the items) therefore I want to know what the best way to make the ComboBox set the SelectedItem if there is only 1 item in the ItemsSource, otherwise leave it as null to ensure the user chooses an account.
The way I am doing this at the moment is by checking the account collection each time it is changed, and if it contains only one, setting the bound selected item property to the first item in the collection.
This seems long winded and I would need to implement it into each view model separately and write up to 5 lines of code for each combo box.
The following is the code I currently, but I was wondering if there would it be possible to achieve this by extending the ComboBox control? And if anyone has any ideas on how/where to start.
public CompanyGermanPower FromCompany
{
get { return _fromCompany; }
set
{
SetField(ref _fromCompany, value, () => FromCompany);
if(value!= null)
{
FromTradeAccountList = new ObservableCollection<TradeAccount>(TradeAccountAdapter.GetTradeAccounts(_session, value.ID));
if (Trade != null && FromTradeAccountList.Count == 1) Trade.TradeAccountFrom = FromTradeAccountList[0];
}
}
} private CompanyGermanPower _fromCompany;