Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get ListBox and UpdateTarget to work

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?

like image 653
RobSullivan Avatar asked Sep 10 '09 20:09

RobSullivan


1 Answers

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.

like image 73
Noldorin Avatar answered Oct 25 '22 03:10

Noldorin