I have a strange problem with a ListBox: I have bound it to a Collection that does not implement INotifyCollectionChanged (Not possible as it's items are dynamically generated on request):
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var metaData in Metadata.Where((m) => m.IsEnabled))
{
yield return new DynamicPropertyValue(this, metaData);
}
}
Therefore, when IsVisible of the ListBox changes, I'm trying to force to update the ItemsSource by setting it to Null and then update the binding:
static void ItemsControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (true.Equals(e.NewValue))
{
var element = (ItemsControl)sender;
var bindingExpression = BindingOperations.GetBindingExpression(element, ItemsControl.ItemsSourceProperty);
if (bindingExpression != null)
{
element.SetCurrentValue(ItemsControl.ItemsSourceProperty, null);
bindingExpression.UpdateTarget();
var count = element.ItemsSource.OfType<object>().Count();
if (count != element.Items.Count)
{
Debug.WriteLine("Wrong number of items");
}
}
}
}
When the ItemsSource is set to Null, the ItemsControl does not contain any items any more and the Items collection is empt, as expected. However, when applying the binding again, all old items are restored. The Items collection contains the same instances as before. The GetEnumerator method is called, but the new items are ignored.
I don't understand why this is the case or how I can avoid that the ItemsControl caches its Items.
Alex
element.SetCurrentValue(ItemsControl.ItemsSourceProperty, null);
I believe this will only set yourItemsControl.ItemSource
tonull
, where is your code to update the collection? – Bolu