2009-11-12 75 views
0

我想創建一些自定義的treeviews。到目前爲止,一切正常,但我遇到了一些風格問題。我有一個簡單的「RedBackground」風格,我將它添加到Window的資源中。添加普通元素時,它可以正常工作。FrameworkElementFactory「忽略」父資源(例如樣式)

當使用自定義項目模板渲染樹視圖項目時,我的資源將被忽​​略。如果我直接添加資源到模板,它工作正常(在代碼中標記)...

我明顯不希望添加樣式到ItemTemplate direclty,在進一步的開發中會非常複雜。我認爲我錯過了某種「綁定」或「查找」......我認爲它與依賴屬性有關......或者是在這個方向上。

也許任何人有更多的見解,這裏是創建模板的代碼(UTIL類中,但那只是爲了讓所有的清潔):

var hdt = new HierarchicalDataTemplate(t) 
         { 
          ItemsSource = new Binding("Children") 
         }; 

     var tb = new FrameworkElementFactory(typeof (TextBlock)); 
     tb.SetBinding(TextBlock.TextProperty, new Binding("Header")); 

     hdt.VisualTree = tb; 

     // This way it works... 
     TextBlockStyles.AddRedBackground(hdt.Resources); 

     return hdt; 

在這裏,我很簡單的自定義樹視圖

public class TreeViewCustom<T> : TreeView 
{ 
    public TreeViewCustom() 
    { 
     MinWidth = 300; 
     MinHeight = 600; 

     ItemTemplate = TreeViewTemplates.TryGetTemplate(typeof(T)); 

     // This is ignored.... (Also when set as resource to window) 
     TextBlockStyles.AddRedBackground(Resources); 
    } 
} 

好,而且可以肯定的,在這裏它創建樣式代碼:任何TI

public static class TextBlockStyles 
{ 
    public static void AddRedBackground(ResourceDictionary r) 
    { 
     var s = CreateRedBackground(); 
     r.Add(s.TargetType, s); 
    } 


    private static Style CreateRedBackground() 
    { 
     var s = new Style(typeof(TextBlock)); 

     s.Setters.Add(new Setter 
     { 
      Property = TextBlock.BackgroundProperty, 
      Value = new SolidColorBrush(Colors.Red) 
     }); 

     return s; 
    } 

} 

謝謝ps ... Chris

回答