📅  最后修改于: 2023-12-03 14:39:44.687000             🧑  作者: Mango
在WPF中,DataGrid是一个常用的控件,它允许我们以表格的方式展示数据。有时候我们需要添加一些额外的列来展示一些计算后的结果或者是一些操作按钮。本文将介绍如何在DataGrid中添加额外的列。
我们可以通过以下步骤来给DataGrid添加额外的列:
<DataGrid.Columns>
<DataGridTextColumn Header="" Binding="{Binding}"></DataGridTextColumn>
</DataGrid.Columns>
myDataGrid.ItemsSource = myDataList.Select(d => new
{
Data = d,
ExtraColumn1 = CalculateExtraColumn1(d),
ExtraColumn2 = CalculateExtraColumn2(d),
// 更多的额外列
}).ToList();
其中,myDataList
是原始数据源,CalculateExtraColumn1
和CalculateExtraColumn2
是计算额外列的方法。
<DataGrid.Columns>
<DataGridTextColumn Header="Column1" Binding="{Binding Data.Column1}"></DataGridTextColumn>
<DataGridTextColumn Header="Column2" Binding="{Binding Data.Column2}"></DataGridTextColumn>
<!-- 更多的原始列 -->
<DataGridTextColumn Header="ExtraColumn1" Binding="{Binding ExtraColumn1}"></DataGridTextColumn>
<DataGridTextColumn Header="ExtraColumn2" Binding="{Binding ExtraColumn2}"></DataGridTextColumn>
<!-- 更多的额外列 -->
</DataGrid.Columns>
这样就完成了添加额外列的操作。
以下是一个完整的例子,展示如何添加两个额外列:
XAML:
<Window x:Class="MyProject.MainWindow"
...
xmlns:local="clr-namespace:MyProject">
<Grid>
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="" Binding="{Binding}"></DataGridTextColumn>
<DataGridTextColumn Header="Column1" Binding="{Binding Data.Column1}"></DataGridTextColumn>
<DataGridTextColumn Header="Column2" Binding="{Binding Data.Column2}"></DataGridTextColumn>
<DataGridTextColumn Header="ExtraColumn1" Binding="{Binding ExtraColumn1}"></DataGridTextColumn>
<DataGridTextColumn Header="ExtraColumn2" Binding="{Binding ExtraColumn2}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<MyData> myDataList = new List<MyData>
{
new MyData { Column1 = "A", Column2 = "B" },
new MyData { Column1 = "C", Column2 = "D" },
};
myDataGrid.ItemsSource = myDataList.Select(d => new
{
Data = d,
ExtraColumn1 = CalculateExtraColumn1(d),
ExtraColumn2 = CalculateExtraColumn2(d),
}).ToList();
}
private static string CalculateExtraColumn1(MyData myData)
{
return myData.Column1 + myData.Column2;
}
private static string CalculateExtraColumn2(MyData myData)
{
return myData.Column1.ToUpper() + myData.Column2.ToLower();
}
}
public class MyData
{
public string Column1 { get; set; }
public string Column2 { get; set; }
}
在给DataGrid添加额外列时,需要注意以下事项: