Sum Datagrid列

时间:2017-11-06 14:12:53

标签: c# wpf

我想在添加新行时对简化的数据网格进行总结,但我不知道如何做到这一点。有人能告诉我怎么会这样做吗?

感谢您一如既往的帮助。

   XAML
   <Grid>
    <DataGrid x:Name="ResultsDataGrid" HorizontalAlignment="Left" Margin="87,41,0,0" VerticalAlignment="Top" Height="134" Width="835" CanUserAddRows="False" CanUserDeleteRows="False" />
    <Button x:Name="AddResult" Content="Add Row" HorizontalAlignment="Left" Margin="847,179,0,0" VerticalAlignment="Top" Width="75" Click="AddResult_Click"/>
    <TextBox x:Name="noofrows" HorizontalAlignment="Left" Height="19" Margin="813,180,0,0" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="29"/>
    <Label x:Name="label" Content="No. of Rows" HorizontalAlignment="Left" Margin="741,177,0,0" VerticalAlignment="Top"/>
</Grid>

   c#
   public class AddResultRow
{
    public string InspectionFee { get; set; }
}

public partial class MainWindow : Window
{
    public ObservableCollection<AddResultRow> _items = new ObservableCollection<AddResultRow>();

    public MainWindow()
    {
        InitializeComponent();
        ResultsDataGrid.ItemsSource = _items;
    }

    private AddResultRow addnewrow()
    {
        return new AddResultRow()
        {
            InspectionFee = ""
        };
    }

    public void AddResult_Click(object sender, RoutedEventArgs e)
    {
        _items.Add(addnewrow());
        int rowCount = ResultsDataGrid.Items.Count;
        noofrows.Text = rowCount.ToString();
    }
}

2 个答案:

答案 0 :(得分:2)

尝试类似:

using System.Linq;
public int SumOfFees() {
   return items_.ToList().Where(x => Int32.TryParse(x.InspectionFee, out var result)).Sum(x => Int32.Parse(x.InspectionFee));
}

答案 1 :(得分:0)

查看MSDN about Grouping Sorting他们提供完整的工作示例,其中包括总计行数。在示例中,他们提供itemCount(而非sum),但他们提供的completeConverter是逐行计算,您可以使用它来创建总和以及其他类型的&#39;每行&#39;评估。 grouping, sorting, totals and filters