【发布时间】:2019-01-30 17:45:09
【问题描述】:
我在 StackOverflow 上搜索,但似乎找不到答案。我是 WPF 的新手,我真的对 xaml 部分感到困惑。那么如何从下面做一个像xml这样的结构呢?
我正在尝试为此 xml 构建一个视图:
<?xml version="1.0" encoding="utf-8"?>
<Patients>
<Patient>
<ID>44</ID>
<Name>Ben Garsia</Name>
<Year>1985</Year>
</Patient>
<Patient>
<ID>22</ID>
<Name>Melisa Mayer</Name>
<Year>1968</Year>
</Patient>
<Patient>
<ID>33</ID>
<Name>Morgan Smith</Name>
<Year>1979</Year>
</Patient>
</Patients>
并希望Treeview完全一样,所以首先将Patients作为一个节点,然后当我展开它时,有三个节点“Patient”,然后是Patient的相关内容。
相反,我得到了这个:
Patients
44Ben Garsia1985
22Melisa Mayer1968
33Morgan Smith1979
这是我的 xaml:
<Window x:Class="LoadTreeView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LoadTreeView"
Title="MainWindow" Height="450" Width="800">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TreeView Name="treeViewT">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:PatientsList}" ItemsSource="{Binding Patients}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Patients" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:Patient}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ID}" />
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Year}" />
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
<StackPanel Orientation="Horizontal" Grid.Row="1" HorizontalAlignment="Center">
<Button x:Name="btnLoad" Content="Load file" Width="100" Click="button_Click"
HorizontalAlignment="Left" Margin="4" VerticalAlignment="Top"/>
</StackPanel>
</Grid>
还有我用过的类:
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Patient
{
public int ID { get; set; }
public string Name { get; set; }
public int Year { get; set; }
}
[XmlRootAttribute("Patients")]
public class PatientsList
{
[XmlElement("Patient")]
public Patient[] Patients { get; set; }
}
在 xaml 后面的代码中,我这样填充它:
var patientsList = new List<PatientsList>();
patientsList.Add(patients);
treeViewT.ItemsSource = patientsList;
【问题讨论】: