tags:

views:

96

answers:

1

Hello,

I am trying to create some custom treeviews. Everything is working fine so far, but I got a little problem with styles. I have a simple "RedBackground" Style which I add to the resources of the Window. When adding normal elements, it works fine.

When using a custom item template to render treeview items, my resource is ignored. If I add the resource directly to the template it works fine (as marked in code)...

I obviously do not want to have to add styles to the ItemTemplate direclty, would be very complicated in further development. I think I am missing some kind of "Binding" or "Lookup"... I think it is related to dependency properties... Or something in this direction.

Perhaps anyone has more insights, here is the code creating the template (inside util class, but thats just to keep all clean):

 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;

And here my very simple custom tree view

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

Ok, and to be sure, here the code which creates the Style:

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

}

Thanks for any tips... Chris

A: 

Is this a problem with "inheritance"? Not all properties are inherited, read more here:

Property Value Inheritance: http://msdn.microsoft.com/en-us/library/ms753197.aspx

macias