我有一个页面上有许多字段,我用它来创建一个名为Account的新类记录。其中一个字段是通过组合框设置的货币代码。组合框绑定到具有id和描述的数据表。我正在尝试使用绑定,以便组合框的selectedvalue自动更新Account类的货币ID。到目前为止没有快乐......
班级定义:
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定义:
<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}"/>
页面构造函数:
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;
}
保存代码:
private void btnAccountOK_Click(object sender, RoutedEventArgs e)
{
Account newAccountRec = (Account)base.DataContext;
int newid = _DBUtils.AddAccount(newAccountRec);
}
答案 0 :(得分:1)
由于ComboBox的DataContext设置为Account实例,因此其SelectedValue应绑定到CurrencyID
,而不是Account.CurrencyID
:
<ComboBox SelectedValue="{Binding Path=CurrencyID, ...}" ... />
另外(如果你的数据表是DataTable)根据blindmeis的建议,从ComboBox项目的每个表行创建一个具有适当属性的对象集合:
cboCurrency.DisplayMemberPath = "Name";
cboCurrency.SelectedValuePath = "Id";
cboCurrency.ItemsSource =
_DBUtils.getCurrencyList().Rows.Cast<DataRow>().Select(
row => new { Name = row["Name"], Id = row["_id"] });
答案 1 :(得分:0)
你可以使用匿名类型来更容易绑定(每次更改getcurrecylist时都必须设置itemssource)
代码未经过测试:
//i assume that your columns names are "Name" and "_id"
cboCurrency.DisplayMemberPath = "Name";
cboCurrency.SelectedValuePath = "Id";
cboCurrency.ItemsSource = _DBUtils.getCurrencyList().AsEnumerable().Select(x => new {Name = x["Name"], Id = x["_id"]}).ToList;
//lostfocus makes no sense or?
SelectedValue="{Binding Path=CurrencyID, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=true}"