简体   繁体   中英

WPF Datagrid rows do not get cleared - C#

I have a datagrid ; Printreport populated via an observable collection ; PopulatePatternData It runs fine and all rows are displayed when the program is run. When the program is rerun, I would like to get the datagrid updated with the new data rows but instead new data gets added with the previous results (rows)

XAML:

<DataGrid x:Name="PrintReport" ItemsSource="{Binding PopulatePatternData}" AutoGenerateColumns="False" FontFamily="Tahoma" FontSize="12" CanUserSortColumns="False"
                                                     HorizontalContentAlignment="Stretch"  VerticalContentAlignment="Stretch"  AlternatingRowBackground="Gainsboro"  AlternationCount="1" 
                                                     SelectionMode="Extended" SelectionUnit="Cell" >

The button (RunAnalysis) that I use to run the program has an event handler . I clear the observable collection when it is clicked and then the datagrid is created. I tried to " clear " the datagrid rows as shown below but to no avail.

 private void RunAnalysis(object sender, RoutedEventArgs e)
        {
            WFPlanningCompliancePluginModel model = DataContext as WFPlanningCompliancePluginModel;
            model.PopulatePatternData.Clear();
            PrintReport.Items.Clear();   // This does not work         
            model.Run();
        }

The collection gets cleared but not the datagrid ! what am i dong wrong? The program fails when it is run the first time if I use

PrintReport.Items.Clear(); as it does not find any items. 

Rebind the DataGrid after clearing the items:

private void RunAnalysis(object sender, RoutedEventArgs e)
{
    WFPlanningCompliancePluginModel model = DataContext as WFPlanningCompliancePluginModel;
    model.PopulatePatternData.Clear();

    // PrintReport.Items.Clear();   // This you can skip if the binding works.
    PrintReport.DataBind(); // This should be enough if the binding works correctly!
    model.Run();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM