2013-08-31 43 views
5

Tôi ràng buộc dữ liệu đến cơ sở dữ liệu mẫu cho ListBoxItem's, dưới đây là các mã:Listbox Databinding trong WPF

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

Và trong XAML, có mã bên dưới:

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

Nhưng nó không hoạt động, nó cho thấy tên bảng, nhưng tôi cần phải nhìn thấy tên người dùng đến từ bảng, có cột được gọi là UserName trong TblUsers.

Cảm ơn trước.

Trả lời

5

thử này

Tạo DataTemplate trong phần tài nguyên và sau đó gán nó vào listbox

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

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

     </DataTemplate> 

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

Thanks @geek it worked, Thank you very much –

0

Kể từ khi ItemsSource được thiết lập đã có trong mã phía sau, thiết lập các DisplayMemberPath để UserName trong 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">