2014-09-24 92 views
2

這是WPF的第一次體驗,所以請原諒我,我知道這是非常基本的,但我不能得到它的工作。我只是試圖將一個組合框綁定到LINQ到EF填充的ObservableCollection。當我遍歷代碼時,我看到該集合已填充,但組合框不顯示集合的內容。WPF綁定組合框到LINQ填充的Observable集合

這裏是我的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" /> 

我在做什麼錯?任何援助將不勝感激。

回答

3

您綁定到路徑「網站」,但您的屬性名稱爲「SiteCollection」。

您綁定到屬性,所以名稱必須匹配。還要確保您的數據上下文已設置爲您的視圖模型對象。

+0

哇感謝@BradleyDotNET。我無法相信我沒有注意到這一點。這很簡單,我很尷尬。 – mack 2014-09-24 20:37:18

+0

@mack請注意,您應該在輸出窗口中看到System.Data異常,例如「無法在對象MainWindowViewModel上找到屬性站點」。這些錯誤通常會幫助你更快地找到這個東西:) – BradleyDotNET 2014-09-24 20:38:13

+0

感謝@BradleyDotNET,我現在在輸出窗口中看到了這一點。我將來會更加重視這一點! :) – mack 2014-09-24 20:46:47