wpf wpf中的列表框数据绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18547598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Listbox Databinding in wpf
提问by Ahmad Gulzar
I am binding the data coming form database to ListBoxItem's, below is the code:
我将来自数据库的数据绑定到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;
}
And in XAML, there is the below code:
在 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">
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.
但它不起作用,它显示表名,但我需要查看来自表的用户名,TblUsers 中有名为 UserName 的列。
Thanks in Advance.
提前致谢。
回答by santosh singh
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}"/>
回答by Anusha Busetty
Since the ItemsSource is set already in code behind, set the DisplayMemberPath to UserName in XAML.
由于 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">

