【问题标题】:Listbox Databinding in wpfwpf中的列表框数据绑定
【发布时间】:2013-08-31 11:23:18
【问题描述】:

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

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">

但它不起作用,它显示表名,但我需要查看来自表的用户名,在 TblUsers 中有一个名为 UserName 的列。

提前致谢。

【问题讨论】:

    标签: c# wpf xaml listbox


    【解决方案1】:

    试试这个

    在资源部分创建DataTemplate,然后将其分配给列表框

    <Grid.Resources>
            <DataTemplate x:Key="userNameTemplate">
    
                    <TextBlock Text="{Binding Path=UserName}"/>
    
            </DataTemplate>
    

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

    【讨论】:

      【解决方案2】:

      由于 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">
      

      【讨论】:

        猜你喜欢
        • 2010-11-24
        • 1970-01-01
        • 2010-12-15
        • 2014-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-14
        相关资源
        最近更新 更多