Updating a binding that is bound to object[property] (Binding.IndexerName weirdness)
This emerged from my related question. I currently have the following binding:
myBinding = Binding("[foo]")
myBinding.Mode = System.Windows.Data.BindingMode.TwoWay
myBinding.Source = obj
acheckbox.SetBinding(CheckBox.IsCheckedProperty, myBinding)
acheckbox.DataContext = obj
This will look at obj[foo]
. The UI will update the source just fine - I can check the checkbox and obj[foo]
is changed. However, the reverse is not working. Changing obj[foo]
in code does not update the UI, even with this code manually calling OnPropertyChanged
:
obj[foo] = False
obj._OnPropertyChanged(obj, System.ComponentModel.PropertyChangedEventArgs("[foo]"))
The problem likely lies with the arguments to OnPropertyChanged
. Some digging (and help from H.B.) revealed this post:
http://10rem.net/blog/2010/03/08/wpf---silverlight-quick-tip-inotifypropertychanged-for-indexer
If you're creating the data source for those (for example, you are building your own ObservableDictionary), you may wonder how on earth you fire the appropriate
INotifyPropertyChanged.PropertyChanged
event to let the binding system know that the item with that field name or index has changed.The binding system is looking for a property named
"Item[]"
, defined by the constant stringBinding.IndexerName
.
In other words, Binding.IndexerName
is a constant, "Item[]"
, that tells the binding engine to rescan the whole source dictionary.
obj._OnPropertyChanged(obj, System.ComponentModel.PropertyChangedEventArgs(Binding.IndexerName))
# equivalent to:
obj._OnPropertyChanged(obj, System.ComponentModel.PropertyChangedEventArgs("Item[]"))
Unfortunately, scanning the entire source dictionary happens to be an expensive operation in my code; so that post also talks about using "Item[foo]"
as the argument. Thi开发者_Python百科s is exactly what I need - and it doesn't work! Only Item[]
works. Why?
According to mamadero2 in this thread Item[index]
only works in Silverlight 4.
(I never would have imagined that Silverlight supports something that WPF does not)
精彩评论