WPF绑定组合框到LINQ填充的Observable集合
问题描述:
这是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" />
我在做什么错?任何援助将不胜感激。
答
您绑定到路径“网站”,但您的属性名称为“SiteCollection”。
您绑定到属性,所以名称必须匹配。还要确保您的数据上下文已设置为您的视图模型对象。
哇感谢@BradleyDotNET。我无法相信我没有注意到这一点。这很简单,我很尴尬。 – mack 2014-09-24 20:37:18
@mack请注意,您应该在输出窗口中看到System.Data异常,例如“无法在对象MainWindowViewModel上找到属性站点”。这些错误通常会帮助你更快地找到这个东西:) – BradleyDotNET 2014-09-24 20:38:13
感谢@BradleyDotNET,我现在在输出窗口中看到了这一点。我将来会更加重视这一点! :) – mack 2014-09-24 20:46:47