I have a page with a number of fields on it that I’m using to create a new class record called Account. One of the fields is a currency code that is set via a combobox. The combobox is bound to a datatable with an id and a description. I’m trying to use binding so that the selectedvalue of the combobox automatically updates the currency id of the Account class. So far no joy…
Class definition:
class Account : IDataErrorInfo
{
public String Name { get; set; }
public int CurrencyID { get; set; }
public int BankID { get; set; }
public String AccountNumber { get; set; }
public decimal OpeningBalance { get; set; }
... other definitions for validation handling ...
}
Combobox definition:
<ComboBox x:Name="cboCurrency" Grid.Column="1" Grid.Row="1" Width="250" HorizontalAlignment="Left"
SelectedValue="{Binding Path=Account.CurrencyID, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=true}"
ToolTip="{Binding ElementName=cboCurrency, Path=(Validation.Errors)[0].ErrorContent}"/>
Page constructor:
public AccountAdd()
{
InitializeComponent();
base.DataContext = new Account();
// Load the Currency combo with the list of currencies
//
cboCurrency.DisplayMemberPath = "Name";
cboCurrency.SelectedValuePath = "_id";
cboCurrency.ItemsSource = _DBUtils.getCurrencyList().DefaultView;
}
Save Code:
private void btnAccountOK_Click(object sender, RoutedEventArgs e)
{
Account newAccountRec = (Account)base.DataContext;
int newid = _DBUtils.AddAccount(newAccountRec);
}
Since the ComboBox’s DataContext is set to an Account instance, its SelectedValue should bind to
CurrencyID, notAccount.CurrencyID:Also (if your datatable is a DataTable) create a collection of objects with appropriate properties from each table row for the ComboBox’s items, as suggested by blindmeis: