Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF datagrid binding with custom columns

Currently I am working on WPF application (with MVVM) in which I am displaying data in the 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>

Here PartsList is an ObservableCollection of entity Part.

Now I want to add custom column to the DataGrid which shows discount and another column which shows net amount. How can I do this?

Please give a good idea to do this as I need to work with thousands of records so performance is very important for me.

Thank you in advance.

like image 878
rupareliab Avatar asked Aug 09 '13 17:08

rupareliab


1 Answers

Try to add columns on the Loaded event of DataGrid:

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" />
like image 148
yo chauhan Avatar answered Nov 11 '22 07:11

yo chauhan