【问题标题】:Moving WPF control with its templates to a new parent将 WPF 控件及其模板移至新父级
【发布时间】:2013-02-01 20:51:10
【问题描述】:

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

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

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

所以我在让它重新应用模板时遗漏了一些东西。

【问题讨论】:

    标签: c# wpf wpf-controls datatemplate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-10
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-13
      相关资源
      最近更新 更多