简体   繁体   中英

Moving WPF control with its templates to a new parent

Let's jump right in and let the code explain:

            FrameworkElement par = list;
        while((par = par.Parent as FrameworkElement) != null) {
            grid.Resources.MergedDictionaries.Add(par.Resources);
        }
        grid.DataContext = list.DataContext;
        if(rootparent is ContentControl) {
            (rootparent as ContentControl).Content = null;
        } else if(rootparent is Decorator) {
            (rootparent as Decorator).Child = null;
        } else if(rootparent is Panel) {
            rootindex = (rootparent as Panel).Children.IndexOf(list);
            (rootparent as Panel).Children.RemoveAt(rootindex);
        }
        grid.Children.Add(list);

So, basically, the templated control is moved out of its original window and into an instantiated grid in the background. Its datacontext successfully transfers (I watched it go to null when it disconnected, and back to the original object when it joined the grid), but the templates don't. I don't get why, because up there at the top I'm copying all the resource dictionaries all the way to the top-level parent and merging them into the new grid.

So I'm missing something in making it re-apply the templates.

The resources needed to be duplicated into the new container, not just referenced.

FrameworkElement par = list;
while((par = par.Parent as FrameworkElement) != null) {
    DictionaryEntry[] resources = new DictionaryEntry[par.Resources.Count];
    par.Resources.CopyTo(resources, 0);
    var res = new ResourceDictionary();
    foreach(DictionaryEntry ent in resources)
        res.Add(ent.Key, ent.Value);
    grid.Resources.MergedDictionaries.Add(res);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM