将IEnumerated列表与ListBox绑定 [英] Bind IEnumerated List with ListBox

查看:87
本文介绍了将IEnumerated列表与ListBox绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,该代码返回RelationList类型IEnumeration.

Below is my code that returns RelationList type IEnumeration.

public IEnumerable<RelationList> GetRelations(string userID)
  {
      return from relations in dbContext.RelationList
                   where relations.PrimaryUserID == userID
                   select relations;
  }



之后,我使用下面的代码将枚举绑定到ListBox:



After this I use below code to bind the Enumeration with ListBox:

listRelations.ItemsSource = GetRelations(userID);



它绑定并显示适当的行数,但是显示的值是"RelationList".

实际数据在RelationList.UserName



It binds and shows proper number of rows, but values that shows up is "RelationList".

Actual data is in RelationList.UserName

How can I get it to show up in ListBox?

推荐答案

为ListBox提供数据模板:

Provide a DataTemplate for the ListBox :

<ListBox.ItemTemplate>
    <DataTemplate>
         <TextBlock Text="{Binding UserName}"/>
    </DataTemplate>
</ListBox.ItemTemplate>


好,这是对您的回复的回应(某些mod会转至评论或您的原始问题).您现在拥有:

Ok, this is in response to your response (which some mod will move to a comment, or to your original question). You now have:

<ListBox Height="367" HorizontalAlignment="Left" Name="listRelations"

       VerticalAlignment="Top" Width="254">
    <DataTemplate>
        <TextBlock Name="txtName" Text="Binding UserName" />
    </DataTemplate>
</ListBox>



你能看到那里出什么问题了吗?您无意中通过将DataTemplate 作为项目添加到ListBoxItems 集合中来设置Items 属性.正确的代码是:



Can you see what''s wrong there? You are inadvertently setting the Items property by adding a DataTemplate as an item in your ListBox''s Items collection. The correct code is:

<ListBox Height="367" HorizontalAlignment="Left" Name="listRelations"

       VerticalAlignment="Top" Width="254">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <TextBlock Name="txtName" Text="{Binding UserName}" />
      </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


这篇关于将IEnumerated列表与ListBox绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆