gpt4 book ai didi

WPF ComboBox 绑定(bind)未按预期工作

转载 作者:行者123 更新时间:2023-12-02 01:08:36 25 4
gpt4 key购买 nike

我希望将 WPF ComboBox 的 ItemsSource 属性绑定(bind)到 MyListObject 的 MyList 属性。问题是,当我在代码中更新 MyList 属性时,WPF ComboBox 没有反射(reflect)更新。我在执行更新后引发 PropertyChanged 事件,并且我认为 WPF 应该通过更新 UI 来自动响应。我错过了什么吗?

这是 CLR 对象:

Imports System.ComponentModel

Public Class MyListObject
Implements INotifyPropertyChanged

Private _mylist As New List(Of String)

Public Sub New()
_mylist.Add("Joe")
_mylist.Add("Steve")
End Sub

Public Property MyList() As List(Of String)
Get
Return _mylist
End Get
Set(ByVal value As List(Of String))
_mylist = value
End Set
End Property

Public Sub AddName(ByVal name As String)

_mylist.Add(name)

NotifyPropertyChanged("MyList")

End Sub

Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub

Public Event PropertyChanged(ByVal sender As Object, _
ByVal e As System.ComponentModel.PropertyChangedEventArgs) _
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

End Class

这是 XAML:

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfApplication1"
>

<Window.Resources>
<ObjectDataProvider x:Key="MyListObject" ObjectType="{x:Type local:MyListObject}"/>
</Window.Resources>

<Grid>

<ComboBox Height="23"
Margin="24,91,53,0"
Name="ComboBox1"
VerticalAlignment="Top"
ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}}"
/>
<TextBox Height="23"
Margin="24,43,134,0"
Name="TextBox1"
VerticalAlignment="Top" />
<Button Height="23"
HorizontalAlignment="Right"
Margin="0,43,53,0"
Name="btn_AddName"
VerticalAlignment="Top"
Width="75">Add</Button>
</Grid>
</Window>

这是简单的隐藏代码:

Class Window1 

Private obj As New MyListObject

Private Sub btn_AddName_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) _
Handles btn_AddName.Click

obj.AddName(TextBox1.Text)

End Sub
End Class

谢谢!

最佳答案

您正在绑定(bind)到字符串列表。该列表类没有实现 Inotifyproperty。您应该使用可观察集合来代替。我还注意到在你声明后面的代码中

Private obj As New MyListObject

这不是您将组合框绑定(bind)到的静态资源。因此您的添加调用不会反射(reflect)在您的 View 中。

关于WPF ComboBox 绑定(bind)未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/240946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com