我正在尝试创建一些自定义树视图。到目前为止一切都很好,但我在样式方面遇到了一点问题。我有一个简单的“RedBackground”样式,我将它添加到 Window 的资源中。添加普通元素时,它工作正常。
使用自定义项目模板呈现树视图项目时,我的资源被忽略。如果我将资源直接添加到模板中,它可以正常工作(如代码中标记的那样)......
我显然不希望直接向 ItemTemplate 添加样式,这在进一步开发中会非常复杂。我想我缺少某种“绑定”或“查找”......我认为它与依赖属性有关......或者这个方向的东西。
也许有人有更多的见解,这里是创建模板的代码(在 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);
}
}
好的,可以肯定的是,这里是创建样式的代码:
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;
}
}
感谢您的任何提示...克里斯