在 Silverlight 中,当绑定(bind)到字典时,我无法让 INotifyPropertyChanged 像我希望的那样工作。在下面的示例中,页面绑定(bind)到字典没问题,但是当我更改其中一个文本框的内容时,不会调用 CustomProperties 属性 setter 。 CustomProperties 属性 setter 仅在设置 CustomProperties 时调用,而不是在设置其中的值时调用。我正在尝试对字典值进行一些验证,因此我希望在更改字典中的每个值时运行一些代码。有什么我可以在这里做的吗?
C#
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
MyEntity ent = new MyEntity();
ent.CustomProperties.Add("Title", "Mr");
ent.CustomProperties.Add("FirstName", "John");
ent.CustomProperties.Add("Name", "Smith");
this.DataContext = ent;
}
}
public class MyEntity : INotifyPropertyChanged
{
public event PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged;
public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e);
private Dictionary<string, object> _customProps;
public Dictionary<string, object> CustomProperties {
get {
if (_customProps == null) {
_customProps = new Dictionary<string, object>();
}
return _customProps;
}
set {
_customProps = value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("CustomProperties"));
}
}
}
}
VB
Partial Public Class MainPage
Inherits UserControl
Public Sub New()
InitializeComponent()
Dim ent As New MyEntity
ent.CustomProperties.Add("Title", "Mr")
ent.CustomProperties.Add("FirstName", "John")
ent.CustomProperties.Add("Name", "Smith")
Me.DataContext = ent
End Sub
End Class
Public Class MyEntity
Implements INotifyPropertyChanged
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private _customProps As Dictionary(Of String, Object)
Public Property CustomProperties As Dictionary(Of String, Object)
Get
If _customProps Is Nothing Then
_customProps = New Dictionary(Of String, Object)
End If
Return _customProps
End Get
Set(ByVal value As Dictionary(Of String, Object))
_customProps = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("CustomProperties"))
End Set
End Property
End Class
xml
<TextBox Height="23" Name="TextBox1" Text="{Binding Path=CustomProperties[Title], Mode=TwoWay}" />
<TextBox Height="23" Name="TextBox2" Text="{Binding Path=CustomProperties[FirstName], Mode=TwoWay}" />
<TextBox Height="23" Name="TextBox3" Text="{Binding Path=CustomProperties[Name], Mode=TwoWay}" />
最佳答案
一个集合除了 INotifyCollectionChanged interface 之外还需要实现 INotifyPropertyChanged interface 来支持数据绑定(bind)。 ObservableCollection class 为类似 List 的集合实现了它们,但我相信 .NET Framework 中没有类似字典的集合可以做到这一点。您可能必须自己实现它。