如何通过绑定在组合框上绑定(字符串的)列表



我无法通过绑定将(字符串的(列表绑定为组合框的源。它与一起工作

cb_ListTexts.ItemsSource = cKiosque.ListTexts

但没有

cb_ListTexts.DataContext = cKiosque

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingWPF"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ComboBox x:Name="cb_ListTexts"  SelectedValue="{Binding Path=ckiosque.ListTexts}" HorizontalAlignment="Left" Height="51" Margin="97,121,0,0" VerticalAlignment="Top" Width="367"/>
<TextBox x:Name="tb_SelectedItem" Text="{Binding Path=SelectedValue, ElementName=cb_ListTexts}"  HorizontalAlignment="Left" Height="28" Margin="243,235,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="288"/>
</Grid>
</Window>
Imports System.ComponentModel
Class MainWindow
Private Property cKiosque As New Kiosque
Sub New()
' Cet appel est requis par le concepteur.
InitializeComponent()
' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
cb_ListTexts.DataContext = cKiosque.ListTexts
'cb_ListTexts.ItemsSource = cKiosque.ListTexts
End Sub
End Class
Class Kiosque
Implements INotifyPropertyChanged
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Private Property _ListTexts As New List(Of String)
Private Property _SelectedItem As String
Sub New()
ListTexts.Add("toto")
ListTexts.Add("titi")
End Sub
Public Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs)
If Not PropertyChangedEvent Is Nothing Then
RaiseEvent PropertyChanged(Me, e)
End If
End Sub
Public Property ListTexts As List(Of String)
Get
Return _ListTexts
End Get
Set(value As List(Of String))
_ListTexts = value
'OnPropertyChanged(New PropertyChangedEventArgs("ListTexts"))
End Set
End Property
Public Property SelctedItem As String
Get
Return _SelectedItem
End Get
Set(value As String)
_SelectedItem = value
End Set
End Property
End Class

错误在哪里?

DataContext与ItemsSource不同。示例:您将网格DataContext设置为指向您的Kiosque。然后,每个子级和子级将从网格继承它们的DataContext(级联(。

现在,如果找到绑定,它将尝试将绑定应用于Kiosque对象(称为ViewModel(中{binding Path=MyProperty}的匹配属性名称

要进行调试,我建议您设置此项。DataContext=Kiosque。在窗口的构造函数中。因此,无需设置DataContext。

试试之类的东西

<Grid>
<ComboBox SelectedItem="{Binding SelctedItem}" ItemsSource="{Binding ListTexts}" HorizontalAlignment="Left" Height="51" Margin="97,121,0,0" VerticalAlignment="Top" Width="367"/>
<TextBox Text="{Binding Path=ListTexts}"  HorizontalAlignment="Left" Height="28" Margin="243,235,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="288"/>
</Grid>

请注意:您键入的是SelctedItem而不是SelectedItem。您不需要使用SelectedValue,因为您正在绑定字符串。所选值是绑定到项目的子属性(例如:Engine以显示SelectedCar.Engine的引擎(

最新更新