WPF ListBox - 如何从dataTable中输入值?

时间:2009-11-24 15:41:21

标签: wpf data-binding listbox datatable

我有ListBox并希望将值放在此DataTable的<+ p>列表框中:

listBoxVisibleFields.DataContext = SelectedFields;

SelectedFieldsDataTable填充数据的位置。但是这段代码不起作用。我的ListBox是空的。我记得,在WinForms中,对于像ValueMemberDisplayMember这样的列表框来说是件事,但在WPF中我找不到类似的东西......

有人知道如何从ListBox填写DataTable吗?

2 个答案:

答案 0 :(得分:3)

您要查找的媒体资源为ItemsSource而非DataContext。与ValueMember最相似的属性称为SelectedValuePath(请参阅this example)。 DisplayMember的类比称为DisplayMemberPath


编辑:所以,你的代码应该是这样的:

DataTable SelectedFields = ...;
listBoxVisibleFields.SelectedValuePath = "myID";
listBoxVisibleFields.DisplayMemberPath = "myTextField";
listBoxVisibleFields.ItemsSource = SelectedFields.DefaultView;

或者,可以在XAML中设置两个路径值

<ListBox ... SelectedValuePath="myID" DisplayMemberPath="myTextField" />

更优雅。

答案 1 :(得分:1)

这是我的代码,希望是有用的

Dim connectionString As String = "Data Source=(local);Database=Catalogos;UID=sa;Password=S1santan"
Dim conSQL As New SqlClient.SqlConnection()
conSQL.ConnectionString = connectionString
conSQL.Open()
Debug.Print("SELECT * FROM CodigoPostal WHERE CP= '" & _Codigo & "'")
Dim adaptSQL As New SqlClient.SqlDataAdapter("SELECT * FROM CodigoPostal WHERE CP= '" & _Codigo & "'", conSQL)

Dim DatosCP As New DataSet
adaptSQL.Fill(DatosCP, "CodigoPostal")

'Here you select the table inside a data set
ListBox1.ItemsSource = DatosCP.Tables("CodigoPostal").DefaultView
'Here select which field to show
ListBox1.DisplayMemberPath = "d_asenta"
'and at last here you select the field you want to use to select values from
ListBox1.SelectedValuePath = "ID"

conSQL.Close()