我目前的任务是为 WPF 应用程序构建一个类似电子表格的 GUI,我遇到了一些问题。本质上,我想按列绑定到数据网格,以便一列包含某一年的数据。因此,鉴于 2006 年是开始年,而 2009 年是结束年,我希望有 4 列,每列以列为基础显示给定年份的值。
这就是我现在在代码隐藏中的内容:
private Years m_YearsList;
public Years YearsList
{
get { return m_YearsList; }
set { m_YearsList = value; }
}
public MainWindow()
{
InitializeComponent();
YearsList = LoadData();
TestGrid.DataContext = YearsList;
}
public Years LoadData()
{
var personer = new Years{
new Year
{
Taxed = new Taxed {TaxedField = 10},
NumBuildings = new BuildingsCollection {NumBuildings = 25},
Area = new Area{AreaField = "NoWhere"},
DisplayName = "Person1"
},
new Year
{
Taxed = new Taxed{TaxedField = 2},
NumBuildings = new BuildingsCollection{NumBuildings = 8},
Area = new Area{AreaField = "SomeWhere"},
DisplayName = "Person2"
},
new Year
{
Taxed = new Taxed{TaxedField = 18},
NumBuildings = new BuildingsCollection{NumBuildings = 20},
Area = new Area{AreaField = "UpThere"},
DisplayName = "Person3"
}
};
return personer;
}
}
Year 对象只是简单地包装了两个 int 和一个字符串。Years 对象是我绝望的镜头,看起来像这样:
public class Years : List<Year>{}
我的 XAML:
<DataGrid x:Name="TestGrid" ItemsSource="{Binding}" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=NumBuildings}" />
<DataGridTextColumn Binding="{Binding Path=Taxed}" />
<DataGridTextColumn Binding="{Binding Path=Area}" />
</DataGrid.Columns>
</DataGrid>
此代码生成:
如您所见,Year 对象每列绑定到一个属性,而我基本上希望将它们绑定到一个对象,所有属性都在一个列中。不幸的是,我的 WPF 技能在这里缺乏。:(