c# – 与自定义列绑定的WPF数据网格

前端之家收集整理的这篇文章主要介绍了c# – 与自定义列绑定的WPF数据网格前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
目前我正在研究 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" />

猜你在找的C#相关文章