WPF + ListBox数据绑定系统.data.DataRowView

时间:2014-04-25 11:32:39

标签: c# wpf

我试图在WPF应用程序中从数据库中获取数据后填充Listbox。

我有一个返回DataTable的类

class DataBaseTable
{
    MySqlConnection connection;
    MySqlDataAdapter adapter;
    public DataTable GetTable(String query, String sortBy)
    {
        String connString = "server=localhost;uid=root;pwd=MyNewPass123;database=samprojects;";
        connection = new MySqlConnection(connString);
        adapter = new MySqlDataAdapter(query, connection);
        DataTable dataTable = new DataTable();
        adapter.Fill(dataTable);
        dataTable.DefaultView.Sort = sortBy;          
        return dataTable;
    }
}

和XAML代码

<ListBox Name="listbox1" Width="150" Height="150" SelectionMode="Single" ItemsSource="{Binding}" />

主窗口类

public partial class MainWindow : Window
{
    private DataBaseTable dbTable = new DataBaseTable();
    public MainWindow()
    {
        InitializeComponent();

        listbox1.DataContext = dbTable.GetTable("select name from projects", "name");            
    }
}

但我的列表框已经充满了

  System.Data.DataRowView
  System.Data.DataRowView
  System.Data.DataRowView

无法得到错误的内容?

2 个答案:

答案 0 :(得分:1)

试试这个:

<ListBox Name="listbox1" Width="150" Height="150" SelectionMode="Single" ItemsSource="{Binding}" />
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding name}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

此处还有关于此主题的更多信息:

Data Templates

答案 1 :(得分:1)

默认情况下,控件将显示对象的.ToString()。因为它是一个数据视图,它只显示程序集名称。你想要的是设置DisplayMemberPath

<ListBox Name="listbox1" Width="150" Height="150" SelectionMode="Single" ItemsSource="{Binding}" DisplayMemberPath="MyColumn"/>