简体   繁体   English

WP7 - 列表框绑定

[英]WP7 - listbox Binding

I have an ObservableCollection that I want to bind to my listbox... 我有一个ObservableCollection,我想绑定到我的列表框...

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 contains 2 properties: name and e-mail PersonDetail包含2个属性: 名称和电子邮件

I would like the listbox to have those values for each item in rosterItemsCollection 我希望列表框中包含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";

I would like that listboxes to display the ContactInfo information. 我希望列表框显示ContactInfo信息。

I hope this makes sense... 我希望这是有道理的...

My XAML that I've tried with little success: 我尝试过的XAML收效甚微:

<listbox x:Name="lbRosterList" ItemsSource="rosterItemCollection">
<textblock x:name="itemText" text="{Binding Path=name}"/>

What am I doing incorrectly? 我做错了什么?

Change your Binding Path to this: 将您的绑定路径更改为:

<ListBox x:Name="lbRosterList" DataContext="{Binding}" ItemsSource="{Binding rosterItemCollection}">
<TextBlock x:Name="itemText" Text="{Binding Path=ContactInfo.name}"/>

Then in your code do this (after InitializeComponents in the page constructor): 然后在你的代码中执行此操作(在页面构造函数中的InitializeComponents之后):

lbRosterList.DataContext = App.ViewModel;

Excellent reference for this kind of thing in this free book by Charles Petzold: Chapter 12, pg 363. Charles Petzold在这本免费书中对此类事物的极好参考:第12章,第363页。

You can also remove the DataContext attribute from the listbox and set the DataContext of the page itself. 您还可以从列表框中删除DataContext属性,并设置页面本身的DataContext If you create a new databound application, you will see what I mean with their default example. 如果您创建一个新的数据绑定应用程序,您将看到我们的默认示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM