Listbox ObserverableCollection绑定不起作用

时间:2018-01-11 12:14:17

标签: wpf vb.net binding

我想在xaml中的ObserverableCollection每个绑定中显示我的ListBox,但是当我开始它时,只显示projectname.classname。谢谢你的帮助。

问题:为什么我的列表框会显示projectname.Class2以及如何解决?

这是我的代码:

Imports System.Collections.ObjectModel
Imports System.ComponentModel

Public Class MainWindow
    Implements INotifyPropertyChanged

    Public Property ListWhatever As New ObservableCollection(Of Class2)
    Sub New()
        InitializeComponent()
        Me.DataContext = Me
        Initialize()
    End Sub
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    Sub Initialize()
        ListWhatever.Add(New Klasse2("test"))
        ListWhatever.Add(New Klasse2("hallo"))
    End Sub
End Class

Public Class Class2
    Public Property wort
    Public Sub New(wort As String)
    End Sub
End Class

这是我的xaml:

<ListBox ItemsSource="{Binding Path=ListWhatever}"/>

1 个答案:

答案 0 :(得分:4)

应该有一个DataTemplate,其元素绑定到Class2的属性:

<ListBox ItemsSource="{Binding ListWhatever}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding wort}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

有关详细信息,请参阅Data Templating Overview

您还必须分配wort属性:

Public Class Class2
    Public Property wort As String

    Public Sub New(wort As String)
        Me.wort = wort
    End Sub
End Class