FrameworkElementFactory“忽略”父资源(例如样式)

时间:2009-11-12 20:50:00

标签: c# wpf styles frameworkelementfactory

我正在尝试创建一些自定义树视图。到目前为止一切正常,但我对样式有点问题。我有一个简单的“RedBackground”样式,我添加到Window的资源。添加普通元素时,它可以正常工作。

使用自定义项模板渲染树视图项时,将忽略我的资源。如果我将资源直接添加到模板,它工作正常(在代码中标记)...

我显然不想在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);
    }
}

好的,确定,这里是创建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;
    }

}

感谢您的任何提示...... 克里斯

1 个答案:

答案 0 :(得分:0)

这是“继承”的问题吗?并非所有属性都是继承的,请在此处阅读:

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