目前我正在研究
WPF应用程序(使用MVVM),其中我在DataGridView中显示数据.
<DataGrid RowHeaderWidth="0" ItemsSource="{Binding PartsList,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Item Name" IsReadOnly="True" Width="*" Binding="{Binding ProductName}"></DataGridTextColumn> <DataGridTextColumn Header="Model Name" IsReadOnly="True" Width="*" Binding="{Binding CarModelName}"></DataGridTextColumn> <DataGridTextColumn Header="Company Name" IsReadOnly="True" Width="*" Binding="{Binding CompanName}"></DataGridTextColumn> <DataGridTextColumn Header="Price" IsReadOnly="True" Width="*" Binding="{Binding Rate}"> </DataGrid.Columns> </DataGrid>
这里PartsList是实体Part的ObservableCollection.
现在我想将自定义列添加到显示折扣的DataGrid和显示净金额的另一列.我怎样才能做到这一点?
请提出一个好主意,因为我需要处理成千上万的记录,因此性能对我来说非常重要.
先感谢您.
解决方法
尝试在DataGrid的Loaded事件上添加列:
private void DataGrid_Loaded_1(object sender,RoutedEventArgs e) { dataGrid.Columns.Add((DataGridTextColumn)this.Resources["DiscountColumn"]); dataGrid.Columns.Add((DataGridTextColumn)this.Resources["NetAmountColumn"]); //Alternatively you can create columns in .cs like dataGrid.Columns.Add(new DataGridTextColumn() { Header = "Dicount",Binding = new Binding("Discount") }); dataGrid.Columns.Add(new DataGridTextColumn() { Header = "Net Amount",Binding = new Binding("NetAmount") }); }
<Window.Resources> <DataGridTextColumn x:Key="DiscountColumn" Header="Discount" IsReadOnly="True" Width="*" Binding="{Binding Discount}"/> <DataGridTextColumn x:Key="NetAmountColumn" Header="Net Amount" IsReadOnly="True" Width="*" Binding="{Binding NetAmount}"/> </Window.Resources> <DataGrid RowHeaderWidth="0" x:Name="dataGrid" Loaded="DataGrid_Loaded_1" />