private static DataContextObserver GetInstance(FrameworkElement sender)
{
// Setup initial conditions.
var deadReferences = new List<WeakReference>();
DataContextObserver instance = null;
var wasFound = false;
foreach (var item in instances)
{
// Collect dead references.
if (!item.IsAlive)
{
deadReferences.Add(item);
continue;
}
// Check for match with given source object.
instance = ((DataContextObserver) item.Target);
if (instance.Source == sender)
{
wasFound = true;
break;
}
}
// Remove any dead references that were found while looking up the instance.
RemoveInstances(deadReferences);
// Finish up.
return wasFound ? instance : null;
}