I had an issue where I wanted to force a datacontext to rebind everything. The RaisePropertyChanged(“”) wasn’t working and I like to keep things simple.
I was setting the DataContext = null then setting it back to the desired object right after to force a rebind. This worked well but really pissed off some of the controls. Not everyone appreciates a null databind.
So, what to do. I remember working with virtualization and the DisconnectedItem, a hidden magical gem that Microsoft just finally let us have public access to in 4.5, had magical powers with databinding. It cast a spell that made everyone calm and happy.
The null databinding on the DataContext was causing major slowdowns in the app as all the controls got angry. So I switched the DataContext=null to DataContext = DisconnectedItem.
All was right in the world again and the application became fast again.
Confused, well I am tired. Anyway, here it is in the before and after and it should then make sense. Edited for brevity.
private static object disconnectedItem = null; private void UpdatePropertiesView() { newView.DataContext = null; newView.DataContext = SelectedNode.Node; }
Snippet
private static object disconnectedItem = null; private void UpdatePropertiesView() { if (disconnectedItem == null) disconnectedItem = typeof(System.Windows.Data.BindingExpressionBase).GetField("DisconnectedItem", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); newView.DataContext = disconnectedItem;//force rebind, but gentler. newView.DataContext = SelectedNode.Node; } }
The reason I am doing this is because the Node object didn’t change, but the properties on it did.(a lot of them).
Happy Coding!
PS: Yes, I am adding a check to see if the datacontext is the same so I can skip the null set entirely in those instances…..