WPF游戏道具列表问题:拾取多把钥匙仅显示当前拾取的一把
WPF ListBox仅显示当前拾取钥匙的解决方法
开发WPF游戏时,依次拾取不同房间的key、key2、key3,ListBox每次仅显示当前拾取的钥匙,无法展示所有已拾取的物品。
问题原因
你使用的List(Of String)不实现INotifyCollectionChanged接口,当集合中添加新元素时,无法通知UI进行更新,导致ListBox无法自动刷新显示所有元素。
解决方法
将List(Of String)替换为ObservableCollection(Of String),它会在集合内容发生变化时自动通知UI刷新。同时只需要初始化时绑定一次ItemsSource,无需每次拾取都重复设置。
修改后的代码
Class MainWindow 'declare strings Dim message As String = "" Dim currentRoomName As String 'declare dictionaries Dim start, grassland, underground, sky, castle, beach, underwater, volcano As New Dictionary(Of String, String) Dim currentRoom As Dictionary(Of String, String) '替换为ObservableCollection,支持集合变化通知 Dim gameIteams As New ObservableCollection(Of String) 'declare key true/false Dim key As Boolean = False Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded '窗口加载时绑定一次ItemsSource即可 lstltems.ItemsSource = gameIteams End Sub Private Sub btnGrab__Click(sender As Object, e As RoutedEventArgs) Handles btnGrab_.Click If currentRoomName = "sky" Then gameIteams.Add("key") key = True lbllnfo.Content = "You have the first key" ElseIf currentRoomName = "underground" Then gameIteams.Add("key2") key = True lbllnfo.Content = "You have the Second key" ElseIf currentRoomName = "volcano" Then gameIteams.Add("key3") key = True lbllnfo.Content = "You have the third key" Else lbllnfo.Content = "Nothing here" End If End Sub End Class
说明
ObservableCollection(Of String)是WPF中专门用于数据绑定的集合类型,内置了集合变更通知机制,添加、移除元素时会自动触发ListBox的UI更新。- 移除了每次拾取时重复设置
lstltems.ItemsSource = gameIteams的代码,改为在窗口加载时一次性绑定,避免不必要的重复操作。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

