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

本文关键字:控件 移动 WPF | 更新日期: 2023-09-27 17:56:58

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

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

因此,基本上,模板化控件从其原始窗口移出,并移动到后台的实例化网格中。它的数据上下文成功传输(我看到它在断开连接时变为 null,并在它加入网格时返回原始对象),但模板没有。我不明白为什么,因为在顶部,我将所有资源字典一直复制到顶级父级并将它们合并到新网格中。

所以我在让它重新应用模板时缺少一些东西。

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

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

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