WPF - Refresh contents of a DataTemplate
I have a tab that has its content set to an object (a TFS WorkItem). I have a DataTemplate for the WorkItem type.
When I set the object to the tab it displays nicely.
However, when I update one of the collections on the object (the list of links) this change is not refreshed to the view开发者_StackOverflow中文版.
I have tried making my WorkItem a DependencyProperty and I have also tried setting the value of the tab's content to null then to my object again (in the hopes that it will reload it).
None of this works.
Normally I would just use an observable collection to store the links in, but as I do not own the WorkItem class, I need a different solution that will manually refresh the DataTemplate.
Any ideas?
To force a binding to refresh the UI, call BindingExpression.UpdateTarget. To get the binding expression for a given element (in your case I assume an ItemsSource), use BindingOperations.GetBindingExpression. E.g.
BindingExpression bindingExpr = BindingOperations.GetBindingExpression(linksListBox, ListBox.ItemsSourceProperty);
bindingExpr.UpdateTarget(); // refreshes the ItemsSource
However, this relies on having a reference to the control whose property is bound, which may be difficult if the control is in a DataTemplate. You could try performing an UpdateTarget() on whichever control is hosting the DataTemplate (the Tab?) and whichever property is bound to the WorkItem (the Content property?) but I haven't tested this. (I'd be interested to know if it works!)
精彩评论