簡體   English   中英

將WPF控件及其模板移動到新的父對象

[英]Moving WPF control with its templates to a new parent

讓我們直接進入,讓代碼解釋一下:

            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,當它加入網格時又返回到原始對象),但是模板卻沒有。 我不明白為什么,因為在頂部,我將所有資源字典一直復制到頂級父級,然后將它們合並到新的網格中。

因此,我在重新應用模板方面缺少一些東西。

需要將資源復制到新容器中,而不僅僅是引用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM