【问题标题】:WPF - ComboBox SelectedItem not bindingWPF - ComboBox SelectedItem 未绑定
【发布时间】: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


【解决方案1】:

账单账户是可变的而不是财产--

billAccount = accounts.Where(i => i.TheAccount.AccountId == this.AccountId).First();

改成

BillAccount = accounts.Where(i => i.TheAccount.AccountId == this.AccountId).First();

【讨论】:

  • 我不确定这是不是问题,因为 BillAccount = accounts.Where(i => i.TheAccount.AccountId == this.AccountId).First();在构造函数中发生,它将在绑定完成之前执行。
  • 除非您更新您的属性,否则不会触发井属性更改.. 尝试一下
  • 它不是构造函数中的属性...使用'B'
  • PropertyChanged 不必在他设置它时触发...在视图绑定到视图模型时,构造函数中的所有内容都已经执行。在构造函数中的代码执行时,绑定还没有设置。
  • 您是否尝试通过代码设置您的 SelectedItem?为您的组合框命名,将 selectedItem 设置为实际项目并检查它是否有效。
猜你喜欢
  • 1970-01-01
  • 2011-11-01
  • 2010-10-24
  • 2017-11-09
  • 2012-06-23
  • 2021-10-18
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多