【发布时间】:2020-11-06 20:12:59
【问题描述】:
我在 WPF 项目中有以下类
public class part
{
public string number { get; set; }
public string name { get; set; }
public List<department> departments { get; set; }
}
public class department
{
public string name { get; set; }
public double hours { get; set; }
}
每个部分都包含不同部门的工时列表。我想要实现的是在 WPF 列表视图中查看它。我的问题是我没有找到一个很好的例子来说明如何将对象列表绑定到 listviewitem。我在 Windows 窗体应用程序中有一个类似的案例。在那里我遍历列表中的对象并通过代码创建子项。虽然这也可以通过在代码中创建 gridviewcolumns 来实现,但我相信它也应该可以通过绑定来实现,还是我弄错了?
例子:
public void Test()
{
List<part> list_parts = new List<part>();
List<department> list_departments = new List<department>();
department d = new department();
d.name = "Sawing";
d.hours = 0.3;
list_departments.Add(d);
d = new department();
d.name = "Miling";
d.hours = 12.3;
list_departments.Add(d);
part Test = new part();
Test.name = "Block";
Test.number = "123";
Test.departments = list_departments;
list_parts.Add(Test);
d = new department();
d.name = "Sawing";
d.hours = 1.2;
list_departments.Add(d);
d = new department();
d.name = "Turning";
d.hours = 5.8;
list_departments.Add(d);
d = new department();
d.name = "Finishing";
d.hours = 5.6;
list_departments.Add(d);
d = new department();
d.name = "QA";
d.hours = 0.5;
list_departments.Add(d);
Test = new part();
Test.name = "Cylinder";
Test.number = "234";
list_parts.Add(Test);
lv_parts.ItemsSource = list_parts;
}
}
没有绑定子列表的列表视图的我的 XAML
<ListView x:Name="lv_parts" ItemsSource="{Binding list_parts}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50px"/>
<RowDefinition Height="50px"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="{Binding number}"/>
<Label Grid.Row="1 " Content="{Binding name}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
预期的结果如下所示:
【问题讨论】:
标签: c# wpf listview listviewitem