【发布时间】:2011-03-09 23:48:11
【问题描述】:
我在简单的 Windows Phone 7 页面中以声明方式设置 PivotItem 中包含的 ListBox 的 ItemsSource 时遇到问题。我可以在后面的代码中成功设置 ItemsSource。
这是包含我要绑定到的 ObservableCollection 的类的 sn-p:
sealed class Database : INotifyPropertyChanged
{
//Declare Instance
private static readonly Database instance = new Database();
//Private Constructor
private Database() { }
//The entry point into this Database
public static Database Instance
{
get
{
return instance;
}
}
#region Collections corresponding with database tables
public ObservableCollection<Category> Categories { get; set; }
public ObservableCollection<CategoryType> CategoryTypes { get; set; }
这是我的 XAML 示例:
<ListBox x:Name="CategoriesListBox" Margin="0,0,-12,0" ItemsSource="{Binding Categories}" DisplayMemberPath="Name" />
在我的页面中,我尝试如下设置数据上下文:
this.DataContext = Database.Instance;
但是,除非我在代码中明确设置 ItemsSource,否则绑定不起作用:
CategoriesListBox.ItemsSource = Database.Instance.Categories;
我知道我应该能够以声明方式完成这一切,但是我尝试了许多不同的方式来以声明方式设置 ItemsSource(除了我上面详述的内容)并且没有任何工作。
谁能帮帮我?
更多信息:运行时的输出窗口显示以下内容:System.Windows.Data 错误:无法获取“类别”值(类型“System.Collections.ObjectModel.ObservableCollection`1[BTT.PinPointTime.Entities.Category]” ) 来自“BTT.PinPointTime.WinPhone.Database”(键入“BTT.PinPointTime.WinPhone.Database”)。 BindingExpression: Path='Categories' DataItem='BTT.PinPointTime.WinPhone.Database' (HashCode=99825759);目标元素是'System.Windows.Controls.ListBox'(名称='CategoriesListBox');目标属性是“ItemsSource”(类型“System.Collections.IEnumerable”)。 System.MethodAccessException:尝试访问该方法失败:BTT.PinPointTime.WinPhone.Database.get_Categories() 在 System.Reflection.RuntimeMethodInfo.InternalInvoke(对象 obj,BindingFlags 调用Attr
【问题讨论】:
-
当您说“绑定不起作用”时,您是什么意思?你什么都得不到?你有例外吗?调试输出窗口中是否有任何消息?
-
@madd0 我没有遇到异常,但是输出窗口确实显示了一些细节 - 已将其添加到我的帖子中
标签: xaml data-binding windows-phone-7 observablecollection