Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将WPF控件及其模板移动到新的父级_C#_Wpf_Wpf Controls_Datatemplate - Fatal编程技术网

C# 将WPF控件及其模板移动到新的父级

C# 将WPF控件及其模板移动到新的父级,c#,wpf,wpf-controls,datatemplate,C#,Wpf,Wpf Controls,Datatemplate,让我们直接切入,让代码解释: FrameworkElement par = list; while((par = par.Parent as FrameworkElement) != null) { grid.Resources.MergedDictionaries.Add(par.Resources); } grid.DataContext = list.DataContext; i

让我们直接切入,让代码解释:

            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);
因此,基本上,模板化控件将从其原始窗口移到后台的实例化网格中。它的datacontext成功地传输(我看到它在断开连接时变为null,在加入网格时变回原始对象),但模板没有。我不明白为什么,因为在顶层,我将所有的资源字典复制到顶层父级,并将它们合并到新的网格中


因此,在使其重新应用模板时,我缺少了一些东西。

需要将资源复制到新容器中,而不仅仅是引用

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);
}