WPF Datagrid行不会被清除 - C#

时间:2017-02-12 08:26:41

标签: c# wpf datagrid

我有一个datagrid; Printreport通过observable collection填充; PopulatePatternData 它运行正常,程序运行时会显示所有行。 重新运行程序时,我想使用新数据行更新datagrid,而是使用之前的结果(行)添加新数据

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" >

我用来运行程序的按钮(RunAnalysis)有一个event handler。单击它时清除observable collection,然后创建数据网格。 我试图&#34; clear&#34; datagrid行如下所示,但无济于事。

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

collection被清除但不是datagrid!我错了什么? 如果我使用

,第一次运行时程序会失败
PrintReport.Items.Clear(); as it does not find any items. 

1 个答案:

答案 0 :(得分:1)

清除项目后重新绑定DataGrid

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();
}