我正在尝试创建一些自定义的树形视图。到目前为止,一切都运行得很好,但我在风格上有一点小问题。我有一个简单的"RedBackground“样式,我将其添加到窗口的资源中。当添加普通元素时,它工作得很好。
当使用自定义项模板呈现treeview项时,我的资源被忽略。如果我将资源直接添加到模板中,它可以正常工作(如代码中所示)……
我显然不想在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;
}
}谢谢你的建议..。克里斯
发布于 2010-08-31 17:42:13
这是“继承”的问题吗?并非所有属性都是继承的,请在此处阅读更多内容:
Property Value Inheritance: http://msdn.microsoft.com/en-us/library/ms753197.aspx
https://stackoverflow.com/questions/1725283
复制相似问题