如何通过Binding将List(Of String)绑定到ComboBox?绑定失败排查
ComboBox绑定List(Of String)失败的问题排查与修复
核心错误点
- XAML绑定属性误用:你将ComboBox的
SelectedValue绑定到ckiosque.ListTexts,但SelectedValue是用来绑定选中项的,数据源应该通过ItemsSource属性绑定,两者用途完全混淆。 - DataContext设置错误:代码中你把
cb_ListTexts.DataContext设为cKiosque.ListTexts,若要通过XAML绑定Kiosque类的ListTexts属性,需将DataContext设为cKiosque实例本身,而非它的ListTexts属性。 - 集合类型局限性:
List(Of String)不支持集合变更通知,后续动态增删项无法自动更新UI,建议改用ObservableCollection(Of String)。 - 属性拼写错误:Kiosque类里的选中项属性拼写成
SelctedItem(少了字母e),应修正为SelectedItem,避免后续绑定选中项时出错。
修正后的代码
XAML代码
<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" ItemsSource="{Binding Path=ListTexts}" SelectedValue="{Binding Path=SelectedItem, Mode=TwoWay}" 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>
VB.NET代码
Imports System.ComponentModel Imports System.Collections.ObjectModel Class MainWindow Private Property cKiosque As New Kiosque Sub New() InitializeComponent() cb_ListTexts.DataContext = cKiosque 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 ObservableCollection(Of String) Private Property _SelectedItem As String Sub New() ListTexts.Add("toto") ListTexts.Add("titi") End Sub Public Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs) RaiseEvent PropertyChanged(Me, e) End Sub Public Property ListTexts As ObservableCollection(Of String) Get Return _ListTexts End Get Set(value As ObservableCollection(Of String)) _ListTexts = value OnPropertyChanged(New PropertyChangedEventArgs("ListTexts")) End Set End Property Public Property SelectedItem As String Get Return _SelectedItem End Get Set(value As String) _SelectedItem = value OnPropertyChanged(New PropertyChangedEventArgs("SelectedItem")) End Set End Property End Class
内容的提问来源于stack exchange,提问作者El doctor Sertato
相关产品推荐
相关产品推荐

