【问题标题】:WP7 - listbox BindingWP7 - 列表框绑定
【发布时间】:2011-01-02 03:32:31
【问题描述】:

我有一个想要绑定到列表框的 ObservableCollection...

lbRosterList.ItemsSource = App.ViewModel.rosterItemsCollection;

但是,在那个集合中我还有另一个集合:

 [DataMember]
    public ObservableCollection<PersonDetail> ContactInfo
    {
        get
        {
            return _ContactInfo;
        }
        set
        {
            if (value != _ContactInfo)
            {
                _ContactInfo = value;
                NotifyPropertyChanged("ContactInfo");
            }
        }
    }

PersonDetail 包含 2 个属性:姓名和电子邮件

我希望列表框为 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 信息。

我希望这是有道理的......

我尝试过但收效甚微的 XAML:

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

我做错了什么?

【问题讨论】:

    标签: windows-phone-7


    【解决方案1】:

    将您的绑定路径更改为:

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

    然后在您的代码中执行此操作(在页面构造函数中的 InitializeComponents 之后):

    lbRosterList.DataContext = App.ViewModel;
    

    Charles Petzold 撰写的 free book 中对此类事物的出色参考:第 12 章,第 363 页。

    您还可以从列表框中删除DataContext 属性并设置页面本身的DataContext。如果您创建一个新的数据绑定应用程序,您会明白我在他们的默认示例中的意思。

    【讨论】:

    • 我下载了那本书并专门查看了该页面。我试过你的建议,虽然看起来有些绑定正在发生,但“名称”属性的文本没有显示......
    • 这对你有用吗,或者你能得到别的东西吗?
    • 实际上我改变了方向......我确实浏览了那本书,它是一个很好的资源。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多