我正在尝试使用数据绑定填充组合框.Below是我的代码的片段。
XAML:
<ComboBox Name="cmbClientName" ItemsSource="{Binding Path=blClientList}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedValue="{Binding Path=blClientList}"/>
'MainWindow'背后的代码:
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Dim blClientList As ObservableCollection(Of String) = New ObservableCollection(Of String)
Dim objClientRepository As PET_ClientRepository = New PET_ClientRepository
For Each objClient As PET_Client In objClientRepository.GetAll()
blClientList.Add(objClient.Name)
Next
Me.cmbClientName.ItemsSource = blClientList
End Sub
Class1.vb:
Public Property Name As String
Get
Return _Name
End Get
Set(value As String)
_Name = value
End Set
End Property
我想在组合框中看到客户端的名称。上面的代码没有返回任何内容,组合框是空白的。我知道问题在于绑定但是无法弄清楚我做错了什么。
答案 0 :(得分:0)
替换它:
Me.cmbClientName.ItemsSource = blClientList
用这个:
Me.DataContext = blClientList
并将XAML更正为:
<ComboBox Name="cmbClientName" ItemsSource="{Binding}"
DisplayMemberPath="." SelectedValuePath="."/>
答案 1 :(得分:0)
这是一个可以帮助您实现理想结果的示例:
Re:你的评论,绑定是好的,你只需要设置上下文
WPF
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4VB"
Title="MainWindow" Height="100" Width="293">
<Window.DataContext>
<local:Vm />
</Window.DataContext>
<Grid>
<ComboBox ItemsSource="{Binding Collection}" DisplayMemberPath="Name" />
</Grid>
</Window>
重要的是你添加本地命名空间:
xmlns:local="clr-namespace:WpfApplication4VB"
并设置DataContext
类
Public Class Vm
Public Property Collection As System.Collections.ObjectModel.ObservableCollection(Of Thing)
Public Sub New()
Collection = New ObjectModel.ObservableCollection(Of Thing)()
Collection.Add(New Thing("Test1"))
Collection.Add(New Thing("Test2"))
Collection.Add(New Thing("Test3"))
End Sub
End Class
Public Class Thing
Public Property Name As String
Public Sub New(Name As String)
Me.Name = Name
End Sub
End Class
答案 2 :(得分:0)
谢谢大家的帮助。
我继续在后面的代码中填充组合框而不是将其绑定到数据源。我甚至不必在XAML中传递“ItemSource”。然而,我确实在Mainwindow.vb中传递了ItemSource,它为我做了诀窍。
以下是正在运行的代码片段:
MainWindow.vb背后的代码
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Me.Username.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim blClientList As ObservableCollection(Of String) = New ObservableCollection(Of String)
Dim objClientRepository As PET_ClientRepository = New PET_ClientRepository
For Each objClient As PET_Client In objClientRepository.GetAll()
blClientList.Add(objClient.Name)
Next
Me.cmbClientName.ItemsSource = blClientList
XAML:
<ComboBox Name="cmbClientName" IsReadOnly="True" PresentationTraceSources.TraceLevel="High"/>
Tracelevel没有做任何事情,只是提供调试跟踪支持。
Class1.vb
Public Property Name As String
Get
Return _Name
End Get
Set(value As String)
_Name = value
End Set
End Property