【问题标题】:WPF Binding Combobox to LINQ Populated Observable CollectionWPF 绑定组合框到 LINQ 填充的可观察集合
【发布时间】:2014-09-25 04:34:05
【问题描述】:

这是第一次使用 WPF,所以请原谅我,我知道这是非常基本的,但我无法让它工作。我只是想将一个组合框绑定到一个 LINQ to EF 填充的 ObservableCollection。当我单步执行代码时,我看到集合已填充,但组合框不显示集合的内容。

这是我的 ViewModel:

public class MainWindowViewModel : ViewModelBase
{
  # region ObservableCollections

  private ObservableCollection<Site> _sitescollection;
  public ObservableCollection<Site> SiteCollection
  {
       get { return _sitescollection;}
       set {
            if (value == _sitescollection) return;
            _sitescollection = value;
            RaisePropertyChanged("SiteCollection");
       }
  }

  # endregion


  public MainWindowViewModel()
  {
       this.PopulateSites();
  }

  // Get a listing of sites from the database
  public void PopulateSites()
  {

       using (var context = new Data_Access.SiteConfiguration_Entities())
       {
            var query = (from s in context.SITE_LOOKUP
                         select new Site(){Name = s.SITE_NAME, SeqId = s.SITE_SEQ_ID });

            SiteCollection = new ObservableCollection<Site>(query.ToList());

       }
  }

}

我的站点类:

public class Site : INotifyPropertyChanged
{
  #region Properties

  string _name;
  public string Name
  {
       get
       {
            return _name;
       }
       set
       {
            if (_name != value)
            {
                 _name = value;
                 RaisePropertyChanged("Name");
            }
       }
  }

  private int _seqid;
  public int SeqId
  {
       get { 
            return _seqid; 
       }
       set { 
            if (_seqid != value)
            {
                 _seqid = value;
                 RaisePropertyChanged("SeqId");
            } 
       }
  }

  #endregion

  #region Constructors
  public Site() { }

  public Site(string name, int seqid)
  {
       this.Name = name;
       this.SeqId = seqid;
  }

  #endregion

  void RaisePropertyChanged(string prop)
  {
       if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); }
  }
  public event PropertyChangedEventHandler PropertyChanged;
}

还有我的 XAML 绑定:

                <ComboBox Margin="10" 
                          ItemsSource="{Binding Sites}"
                          DisplayMemberPath="Name" 
                          SelectedValuePath="SeqId" />

我做错了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您绑定到路径“Sites”,但您的属性名称是“SiteCollection”。

    您绑定到属性,因此名称必须匹配。还要确保您的数据上下文设置为您的视图模型对象。

    【讨论】:

    • 哇,谢谢@BradleyDotNET。我不敢相信我没有注意到这一点。太简单了,我很尴尬。
    • @mack 请注意,您应该在输出窗口中看到 System.Data 异常,上面写着“无法在对象 MainWindowViewModel 上找到属性站点”。这些错误通常可以帮助您更快地找到这些东西:)
    • 感谢@BradleyDotNET,我现在在输出窗口中看到了。以后我会多加注意的! :)
    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2015-03-07
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多