简体   繁体   中英

Listbox Databinding in wpf

I am binding the data coming form database to ListBoxItem's , below is the code:

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;
}

And in XAML, there is the below code:

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

But it does not works, it shows table name, but I need to see the usernames coming from table, there is column called UserName in TblUsers.

Thanks in Advance.

try this

Create DataTemplate in resource section and then assign it to listbox

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

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

        </DataTemplate>

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

Since the ItemsSource is set already in code behind, set the DisplayMemberPath to UserName in XAML.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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