views:

338

answers:

1

Here are the relevant parts of the XAML file:

xmlns:local="clr-namespace:BindingTest"
<ListBox x:Name="myList"
         ItemsSource="{Binding Source={x:Static local:MyClass.Dic},
                               Path=Keys,
                               Mode=OneWay,
                               UpdateSourceTrigger=Explicit}">
</ListBox>

MyClass is a public static class and Dic is a static public property, a Dictionary.

At a certain point I add items to the Dictionary and would like the ListBox to reflect the changes.
This is the code I thought about using but it doesn't work:

BindingExpression binding;
binding = myList.GetBindingExpression(ListBox.ItemsSourceProperty);
binding.UpdateTarget();

This code instead works:

myList.ItemsSource = null;
myList.ItemsSource = MyClass.dic.Keys;

I would prefer to use UpdateTarget, but I can't get it to work.
What am I doing wrong?

+2  A: 

Binding of items is handled rather differently than standard binding of DependencyPropertys in WPF (specifically, by ItemsControls).

I think you want something like the following:

var itemsView = CollectionViewSource.GetDefaultView(myListBox.ItemsSource);
itemsView.Refresh()

It is in fact the ICollectionView object that you want to refresh. This effectively is the object that manages the collection binding for you. See the MSDN page for more info.

Noldorin
Thanks, it worked perfectly.
RobSullivan