XAML noobie在这里! 这就是我现在所拥有的:
现在我需要列出这些并让用户检查一些机器或驱动器,显示一些驱动器信息。我的第一个目标是将我的机器列表绑定到Treeview(对于根元素)和1级孩子的驱动器,但我真的无法做到!
我在做什么:
<TreeView ItemsSource="{Binding MachineList}" Name="treeView1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding DriveList}">
<TextBlock Text="{Binding driveName}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
这里我如何用C#代码声明MachineList:
public ObservableCollection<MyContainerClass.Machine> MachineList{ get; set; }
因为我可以在调试期间验证我的MachineList包含正确的数据(甚至DriveList已正确填充),但我的Treeview上没有显示任何内容。 DriveList是ObservableCollection<MyContainerClass.Drive>
对象。
我做错了什么?
答案 0 :(得分:0)
为HierarchicalDataTemplate设置ItemTemplate,如下所示。
<TreeView ItemsSource="{Binding MachineList}" Name="treeView1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding DriveList}">
<TextBlock Text="{Binding machineName}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding driveName}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
更新(我试过的代码对我有用):
public class Machines
{
private string machinename;
public string machineName
{
get { return machinename; }
set { machinename = value; }
}
private ObservableCollection<DriveList> driveList;
public ObservableCollection<DriveList> DriveList
{
get { return driveList; }
set { driveList = value; }
}
}
public class ViewModel
{
private ObservableCollection<Machines> machines;
public ObservableCollection<Machines> MachineList
{
get { return machines; }
set { machines = value; }
}
public ViewModel()
{
ObservableCollection<DriveList> list= new ObservableCollection<DriveList>();
list.Add(new DriveList() { driveName = "Drive 1" });
machines = new ObservableCollection<Machines>();
machines.Add(new Machines() { machineName = "Machine 1", DriveList =list });
}
}
public class DriveList
{
private string drivename;
public string driveName
{
get { return drivename; }
set { drivename = value; }
}
}