c# - wpf 中的列表框数据绑定(bind)

标签 c# wpf xaml listbox

我将来自数据库的数据绑定(bind)到 ListBoxItem 的,下面是代码:

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 的列。

提前致谢。

最佳答案

试试这个

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

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

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

        </DataTemplate>

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

关于c# - wpf 中的列表框数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547598/

相关文章:

c# - 在 C# 中,我如何使用委托(delegate)来操作我创建的自定义类中的表单?

c# - 需要完全合格的类型名称

wpf - 在 WPF 中对 DataGrid 进行预排序

c# - 在流文档中跨列跨文本

wpf - 设置堆栈面板中所有文本 block 的样式

c# - 无法覆盖 WPF 中 app.xaml 的按钮样式

c# - 当可见性改变时,mdi 子窗体绘制缓慢

c# - WCF 发现.NET 4 : Problem with config/programmatically definition

c# - 如何使用 Nhibernate(和 Fluent NHibernate)映射类型

wpf - 将网格列向右对齐