Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listbox Databinding in wpf

Tags:

c#

wpf

xaml

listbox

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.

like image 681
Ahmad Gulzar Avatar asked Aug 31 '13 11:08

Ahmad Gulzar


People also ask

What is databinding in WPF?

Data binding in Windows Presentation Foundation (WPF) provides a simple and consistent way for apps to present and interact with data. Elements can be bound to data from different kinds of data sources in the form of . NET objects and XML.

What is list box WPF?

ListBox is a control that provides a list of items to the user item selection. A user can select one or more items from the predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction.

What is ItemsSource in WPF?

ItemsSource can be data bound to any sequence that implements the IEnumerable interface, although the type of collection used does determine the way in which the control is updated when items are added to or removed. When ItemsSource is set, the Items property cannot be used to control the displayed values.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.


1 Answers

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}"/>
like image 162
santosh singh Avatar answered Oct 16 '22 08:10

santosh singh