私はここでitowlsonに同意しません。これは厄介な問題ではなく、HierarchicalDataTemplate
この種のことのために作られました。パターンやビューモデル、その他の不要な難読化に無計画に飛び込む前に、2つのクラスと1つのLinq GroupBy
ステートメントで問題を解決できることを考慮してください。
クラスは次のとおりです。
public class GroupItem
{
public string Name
{
get;
private set;
}
public string Group
{
get;
private set;
}
public GroupItem(string name, string group)
{
Name = name;
Group = group;
}
}
public class Group
{
public IEnumerable<GroupItem> Children
{
get;
set;
}
public string Name
{
get;
private set;
}
public Group(string name)
{
Name = name;
}
}
ここまでは順調ですね。必要なすべてのデータを保持するための2つの簡単なクラスがあります。名前とグループは文字列として保存されます。AGroup
にはのコレクションがありGroupItem
ます。今あなたのコードのためにWindow
:
public partial class DistinctLeaves : Window
{
public ObservableCollection<GroupItem> Items
{
get;
set;
}
public IEnumerable<Group> Groups
{
get;
set;
}
public DistinctLeaves()
{
Items = new ObservableCollection<GroupItem>();
Items.Add(new GroupItem("Item A", "Group A"));
Items.Add(new GroupItem("Item B", "Group A"));
Items.Add(new GroupItem("Item C", "Group B"));
Items.Add(new GroupItem("Item D", "Group C"));
Groups = Items.
GroupBy(i => i.Group).
Select(g => new Group(g.Key) { Children = g });
InitializeComponent();
}
}
繰り返しになりますが、これはgroup-by行を除くすべての定型文です。その声明はさらに調査する価値があります。これにより、アイテムコレクションがプロパティに従ってグループ化されGroup
ます。アイテムがグループ化されたら、Group
クラスの新しいインスタンスを作成します。グループのnameプロパティ(キー)を渡し、子をグループ自体に設定します。
最後に、 :Window
を使用するのXAMLを次に示します。HierarchicalDataTemplate
<Window x:Class="TestWpfApplication.DistinctLeaves"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DistinctLeaves" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TreeView ItemsSource="{Binding Groups}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
そしてここに結果があります:
代替テキストhttp://img339.imageshack.us/img339/8555/distinctleaves.jpg