WPF HierarchicalDataTemplate treeview
I have some objects I would like to display using a TreeView
.
The classes I use are defined like this:
public abstract class QueryPart
{
private static Random _random;
protected static Random Random { get { return _random??(_random=new Random(654)); } }
public string Name { get; set; }
public QueryPart()
{
this.Name = this.GetType().Name + " " + Random.Next();
}
}
public abstract class Criterium : QueryPart
{
object ParamValue { get; set; }
protected Criterium()
{
ParamValue = Random.Next();
}
}
public sealed class Criterium<T> : QueryPart
{
}
public abstract class CriteriumGroup : QueryPart
{
public ObservableCollection<QueryPart> Childeren { get; private set; }
public CriteriumGroup()
{
Childeren = new ObservableCollection<QueryPart>();
}
}
public sealed class CriteriumGroup<T> : CriteriumGroup
{
}
public static class Helper
开发者_StackOverflow社区{
public static CriteriumGroup<T> GetDefaultCriteriumGroup<T>()
{
var master = new CriteriumGroup<T>();
master.Childeren.Add(new Criterium<T>());
var sub = new CriteriumGroup<T>()
{
Childeren =
{
new Criterium<T>(),
new Criterium<T>(),
new Criterium<T>(),
new CriteriumGroup<T>()
{
Childeren =
{
new Criterium<T>(),
new Criterium<T>(),
new Criterium<T>()
}
},
new Criterium<T>()
}
};
master.Childeren.Add(sub);
sub = new CriteriumGroup<T>()
{
Childeren =
{
new Criterium<T>(),
new CriteriumGroup<T>()
{
Childeren =
{
new Criterium<T>(),
new Criterium<T>(),
new Criterium<T>()
}
},
}
};
master.Childeren.Add(sub);
return master;
}
}
I would bind the TreeView
to an instance of CriteriumGroup<T>
, and use a HierarchicalDataTemplate
.
The problem is, I can't seem to get it right - my TreeView.Items.Count
is always 0.
This is what I have so far:
<TreeView x:Name="treeview" ItemsSource="{Binding Path=RootCriteriumGroup}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type DynamicLinq:QueryPart}">
<local:QueryPartModelView2/>
</DataTemplate>
<HierarchicalDataTemplate DataType="{x:Type DynamicLinq:Criterium}" ItemsSource={Binding Path=Childeren}>
<local:QueryPartModelView2/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate
DataType="{x:Type DynamicLinq:CriteriumGroup}"
ItemsSource="{Binding Path=Childeren}">
<local:QueryPartModelView2/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
What am I doing wrong?
Taking an approach like this works:
<TreeView Name="treeView1" ItemsSource="{Binding MyEnumerableProperty}" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" >
<StackPanel Orientation="Horizontal">
<Image Source="{Binding MyImageUri}" />
<TextBlock x:Name="someName" Text="{Binding MyNodeText}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
This is a simple way to start, once you have it working you can then look to move things around and have them as Styles and Templates in Resource sections.
精彩评论