我想在WPF中将HierarchicalDataTemplate与TreeView控件一起使用。我创建了一个viewmodel类,但每次程序启动时都会发生System.StackOverflowException。我不知道为什么会这样。
这是WPF标记:
<TreeView Grid.Row="2" ItemsSource="{Binding ImportTasks}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type VM:SyncToolViewModel}" ItemsSource="{Binding Path=ImportTasks}">
<Label Content="{Binding }"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type VM:VmImportTask}" ItemsSource="{Binding Path=ImportTasks.Tables}">
<Label Content="{Binding }"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
这是代码部分:
public class SyncToolViewModel
{
public DBSyncToolLib.DataContext DataContext { get; set; }
private List<VmImportTask> _ImportTasks;
public List<VmImportTask> ImportTasks
{
get
{
if (_ImportTasks == null)
{
_ImportTasks = (from IT in DataContext.ImportTask
select
new VmImportTask()
{
DBImportTask = IT
}
).ToList();
}
return _ImportTasks;
}
}
}
public class VmImportTask
{
public DBSyncToolLib.Schema.ImportTask DBImportTask { get; set; }
public List<VmImportTaskTable> Tables
{
get
{
var L = (from B in DBImportTask.ImportTaskTable
select new VmImportTaskTable()
{
DBImportTaskTable = B
}).ToList();
return L;
}
}
public override string ToString()
{
return this.DBImportTask.Name;
}
}
答案 0 :(得分:0)
我不确定,但是如此
<HierarchicalDataTemplate DataType="{x:Type VM:VmImportTask}" ItemsSource="{Binding Path=Tables}">
左右
<HierarchicalDataTemplate DataType="{x:Type VM:SyncToolViewModel}" ItemsSource="{Binding Path=ImportTasks.Tables}">
答案 1 :(得分:0)
代替HierarchicalDataTemplate,您也可以使用简单的样式。
一个小例子:
public partial class MainWindow : Window
{
public List<Parent> Parents { get; set; }
public MainWindow()
{
InitializeComponent();
this.Parents = new List<Parent>();
this.Parents.Add(new Parent(){ParentName = "Parent1",Childs = new ObservableCollection<Child>(){new Child(){ChildName = "Child1"},new Child(){ChildName = "Child2"}}});
this.Parents.Add(new Parent() { ParentName = "Parent2", Childs = new ObservableCollection<Child>() { new Child() { ChildName = "Child3" }, new Child() { ChildName = "Child4" } } });
this.DataContext = this.Parents;
}
}
public class Parent
{
public string ParentName { get; set; }
public ObservableCollection<Child> Childs { get; set; }
}
public class Child
{
public string ChildName { get; set; }
}
XAML
<TreeView ItemsSource="{Binding}">
<!-- First Level-->
<TreeView.ItemContainerStyle>
<Style>
<Setter Property="TreeViewItem.Header" Value="{Binding ParentName}"/>
<Setter Property="TreeViewItem.ItemsSource" Value="{Binding Childs}"/>
<!-- Second Level -->
<Setter Property="TreeViewItem.ItemContainerStyle">
<Setter.Value>
<Style>
<Setter Property="TreeViewItem.Header" Value="{Binding ChildName}"/>
</Style>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>