【发布时间】:2015-06-28 17:38:54
【问题描述】:
我有两个视图:一个是账单列表,第二个是添加/编辑账单的表单。
BillView 包含一些文本框和一个要填写的组合框。 问题是,如果我在 BillView 打开时尝试编辑账单,文本框将显示我在添加账单时输入的值,但组合框没有显示我在添加账单时选择的值(但列表绑定没问题)。在 BillAccount 集上使用了断点,它似乎可以正常工作,但未设置组合框选定项。
BillView(用于添加/编辑账单):
<Label Grid.Row="5" HorizontalAlignment="Left" Content="Account" />
<ComboBox Grid.Row="5" ItemsSource="{Binding Accounts}" DisplayMemberPath="TheAccount.AccountName" HorizontalAlignment="Right"
SelectedItem="{Binding BillAccount}"/>
这是 BillViewModel 的构造函数:
public BillViewModel(BillModel bill)
{
BillId = bill.TheBill.BillId;
AccountId = bill.TheBill.AccountId;
BillAmmount = (double)bill.TheBill.Ammount;
NextDate = bill.TheBill.NextDate;
this.accounts = GetAccounts(); // populates the list
billAccount = accounts.Where(i => i.TheAccount.AccountId == this.AccountId).First();
}
public AccountModel BillAccount
{
get { return billAccount; }
set { billAccount = value;
OnPropertyChanged("BillAccount");
}
}
GetAccounts() 方法:
private ObservableCollection<AccountModel> GetAccounts()
{
if (accounts == null)
accounts = new ObservableCollection<AccountModel>();
accounts.Clear();
using(var context = new Ents())
{
foreach(var account in context.Accounts)
{
accounts.Add(new AccountModel() { TheAccount = account });
}
}
return accounts;
}
方法应该没问题。
【问题讨论】:
-
您能否查看您的输出窗口以查看是否报告了任何绑定问题?
-
只是为了确定:
Accounts是一个简单地公开accounts字段的属性? -
另外,您也在使用 DisplayMemberPath...您的 AccountModel 对象是否具有“TheAccount”属性?该对象是否具有“AccountName”属性?
-
没有绑定错误。 @Russ 是的,AccountModel 有一个名为 TheAccount 的属性,而 TheAccount 有几个属性,包括 AccountName。
-
能否请您尝试删除 DisplayMemberPath 的使用,并查看 ComboBox 是否显示 BillAccount 属性值的 ToString()?
标签: c# wpf mvvm binding combobox