Reputation: 213
I am creating some attached properties, one of which is a DataTemplate. The DataTemplate should have a FrameworkElement that I've created defined in it so that the XAML declaration of all this looks like:
<SomeControl m:ItemsSource="{Binding Source}">
<m:MyTemplate>
<DataTemplate>
<m:MyClass SomeDependency="{Binding Path}"/>
</DataTemplate>
</m:MyTemplate>
</SomeControl>
In the code for the MyTemplateProperty changed callback, it iterates over every item in Source and calls LoadContent() on the DataTemplate. It then sets the DataContext on the class returned by LoadContent() to the item from Source:
private static void MyTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var items = (d as SomeControl).GetValue(ItemsSourceProperty) as IList;
var template = e.NewValue as DataTemplate;
foreach(var item in items)
{
var myClass = template.LoadContent() as MyClass;
myClass.DataContext = item;
}
}
The strange thing here is that the first instance of MyClass created in this way gets binding updates (SomeDependencyProperty updates with the value that is in the item from ItemsSource), but none of the rest of the instances get updated.
I have verified that this should work properly by creating MyClass myself instead of the LoadContent call and setting the bindings using BindingOperation.SetBinding like:
foreach(var item in items)
{
var myClass = new MyClass();
BindingOperations.SetBinding(myClass, MyClass.SomeDependencyProperty, new Binding("Path");
myClass.DataContext = item;
}
Does anyone know why the LoadContent call seems to produce objects that do not all update their bindings when the DataContext changes? What is different about the LoadContent call than just creating the objects myself?
Upvotes: 2
Views: 486
Reputation: 213
It was pointed out by a co-worker that nothing was holding on to the instances of MyClass. Adding a way for these instances to be referenced solved the issue I was seeing. It doesn't quite explain why the first instance would get updates and the rest wouldn't, but it has fixed my problem.
Upvotes: 2