我有ListBox
并希望将值放在此DataTable
的<+ p>列表框中:
listBoxVisibleFields.DataContext = SelectedFields;
SelectedFields
是DataTable
填充数据的位置。但是这段代码不起作用。我的ListBox
是空的。我记得,在WinForms中,对于像ValueMember
和DisplayMember
这样的列表框来说是件事,但在WPF中我找不到类似的东西......
有人知道如何从ListBox
填写DataTable
吗?
答案 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()