在wpf中绑定列表框数据

6

我正在将来自数据库的数据绑定到 ListBoxItem,以下是代码:

public void load_users()
{
    RST_DBDataContext conn = new RST_DBDataContext();
    List<TblUser> users = (from s in conn.TblUsers
                                  select s).ToList();
    Login_Names.ItemsSource = users;
}

在XAML中,有以下代码:

<ListBox Name="Login_Names" 
         ItemsSource="{Binding Path=UserName}"
         HorizontalAlignment="Left" 
         Height="337" Margin="10,47,0,0"
         Padding="0,0,0,0" VerticalAlignment="Top" Width="156">

但它并没有起作用,它显示了表名,但我需要看到来自表中的用户名,表中有一个称为UserName的列。
提前感谢。
2个回答

8

尝试这个

在资源部分创建DataTemplate,然后将其分配给listbox

<Grid.Resources>
        <DataTemplate x:Key="userNameTemplate">

                <TextBlock Text="{Binding Path=UserName}"/>

        </DataTemplate>

 <ListBox Name="listBox" ItemsSource="{Binding}"
            ItemTemplate="{StaticResource userNameTemplate}"/>

0

由于 ItemsSource 已经在代码后台中设置,因此请在 XAML 中将 DisplayMemberPath 设置为 UserName。

<ListBox Name="Login_Names" 
     DisplayMemberPath="UserName"
     HorizontalAlignment="Left" 
     Height="337" Margin="10,47,0,0"
     Padding="0,0,0,0" VerticalAlignment="Top" Width="156">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接