private void SetElementTemplateScopes (XamlObjectElement element)
{
// This whole thing is basically copied from xaml.cpp AddCreatedItem
DependencyObject el_dob = element.Object as DependencyObject;
if (el_dob == null)
return;
// When instantiating a template, some elements are created which are not explicitly
// mentioned in the xaml. Therefore we need to keep walking up the tree until we find
// the last element which we set a value for Control::IsTemplateItem and propagate
// it from there.
XamlElement instance = CurrentElement;
while (instance != null) {
XamlObjectElement oe = element as XamlObjectElement;
if (oe == null) {
instance = instance.Parent;
continue;
}
DependencyObject dob = oe.Object as DependencyObject;
if (dob == null) {
instance = instance.Parent;
continue;
}
if (dob.ReadLocalValue (Control.IsTemplateItemProperty) == null) {
instance = instance.Parent;
continue;
}
el_dob.SetValue (Control.IsTemplateItemProperty, dob.GetValue (Control.IsTemplateItemProperty));
el_dob.TemplateOwner = dob.TemplateOwner;
break;
}
if (instance == null) {
el_dob.SetValue (Control.IsTemplateItemProperty, Context.IsExpandingTemplate);
el_dob.TemplateOwner = Context.TemplateBindingSource;
}
if (el_dob.GetValue (Control.IsTemplateItemProperty) != null) {
UserControl uc = el_dob as UserControl;
if (uc != null) {
// I can't come up with a test to verify this fix. However, it does
// fix a crasher in olympics when trying to play a new video from
// the recommendations list after the curreont video finishes
NameScope ns = NameScope.GetNameScope (uc);
NameScope.SetNameScope (uc.Content, ns);
NameScope.SetNameScope (uc.Resources, ns);
}
NameScope.SetNameScope (el_dob, NameScope);
}
}