WP7 - 列表框绑定 [英] WP7 - listbox Binding
问题描述
我有一个 ObservableCollection 想绑定到我的列表框...
I have an ObservableCollection that I want to bind to my listbox...
lbRosterList.ItemsSource = App.ViewModel.rosterItemsCollection;
但是,在该集合中,我还有另一个集合:
However, in that collection I have another collection within it:
[DataMember]
public ObservableCollection<PersonDetail> ContactInfo
{
get
{
return _ContactInfo;
}
set
{
if (value != _ContactInfo)
{
_ContactInfo = value;
NotifyPropertyChanged("ContactInfo");
}
}
}
PersonDetail 包含 2 个属性:姓名和电子邮件
PersonDetail contains 2 properties: name and e-mail
我希望列表框为 rosterItemsCollection 中的每个项目都有这些值
I would like the listbox to have those values for each item in rosterItemsCollection
RosterId = 0;
RosterName = "test";
ContactInfo.name = "Art";
ContactInfo.email = "art@something.com";
RosterId = 0;
RosterName = "test"
ContactInfo.name = "bob";
ContactInfo.email = "bob@something.com";
RosterId = 1;
RosterName = "test1"
ContactInfo.name = "chris";
ContactInfo.email = "chris@something.com";
RosterId = 1;
RosterName = "test1"
ContactInfo.name = "Sam";
ContactInfo.email = "sam@something.com";
我希望列表框显示 ContactInfo 信息.
I would like that listboxes to display the ContactInfo information.
我希望这是有道理的...
I hope this makes sense...
我尝试过但收效甚微的 XAML:
My XAML that I've tried with little success:
<listbox x:Name="lbRosterList" ItemsSource="rosterItemCollection">
<textblock x:name="itemText" text="{Binding Path=name}"/>
我做错了什么?
推荐答案
将您的绑定路径更改为:
Change your Binding Path to this:
<ListBox x:Name="lbRosterList" DataContext="{Binding}" ItemsSource="{Binding rosterItemCollection}">
<TextBlock x:Name="itemText" Text="{Binding Path=ContactInfo.name}"/>
然后在您的代码中执行此操作(在页面构造函数中的 InitializeComponents 之后):
Then in your code do this (after InitializeComponents in the page constructor):
lbRosterList.DataContext = App.ViewModel;
Charles Petzold 着的这本免费书籍中对此类事情的出色参考:章节第 12 页,第 363 页.
Excellent reference for this kind of thing in this free book by Charles Petzold: Chapter 12, pg 363.
您还可以从列表框中删除 DataContext
属性并设置页面本身的 DataContext
.如果您创建了一个新的数据绑定应用程序,您将通过默认示例了解我的意思.
You can also remove the DataContext
attribute from the listbox and set the DataContext
of the page itself. If you create a new databound application, you will see what I mean with their default example.
这篇关于WP7 - 列表框绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!