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