0

我有一个页面,上面有许多字段,用于创建一个名为 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 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);
}
4

2 回答 2

1

由于 ComboBox 的 DataContext 设置为 Account 实例,因此其 SelectedValue 应绑定到CurrencyID,而不是Account.CurrencyID

<ComboBox SelectedValue="{Binding Path=CurrencyID, ...}" ... />

此外(如果您的数据表是DataTable)从每个表行中为 ComboBox 的项目创建一个具有适当属性的对象集合,如blindmeis 所建议的那样:

cboCurrency.DisplayMemberPath = "Name";  
cboCurrency.SelectedValuePath = "Id";  
cboCurrency.ItemsSource =
    _DBUtils.getCurrencyList().Rows.Cast<DataRow>().Select(
        row => new { Name = row["Name"], Id = row["_id"] });
于 2012-07-31T10:42:15.220 回答
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}"
于 2012-07-31T11:51:27.980 回答