You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在非WPF应用中展示DataTable生成的月收入计算数据?

解决方案

一、先修正计算逻辑错误

你的代码里收入计算逻辑不符合需求,原代码(Income * Months) * 1.10会导致所有月份收入相同,正确计算应为基础收入 ×1.1 × 当前月份数。同时建议添加输入校验,避免非数字输入引发异常。

二、改用强类型实体类+ObservableCollection(更适合UI绑定)

DataTable在Xamarin/MAUI中绑定体验不如强类型集合,先定义实体类:

public class MonthlyIncomeItem
{
    public int Month { get; set; }
    public decimal Income { get; set; }
}

修改页面代码,实现INotifyPropertyChanged接口通知UI更新:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.Maui.Controls; // Xamarin.Forms项目替换为Xamarin.Forms命名空间

public partial class HomePage : ContentPage, INotifyPropertyChanged
{
    private ObservableCollection<MonthlyIncomeItem> _monthlyIncomeCalculus;
    public ObservableCollection<MonthlyIncomeItem> MonthlyIncomeCalculus
    {
        get => _monthlyIncomeCalculus;
        set
        {
            _monthlyIncomeCalculus = value;
            OnPropertyChanged();
        }
    }

    public HomePage()
    {
        InitializeComponent();
        BindingContext = this; // 设置绑定上下文,让UI能识别绑定属性
    }

    private void calculate(object sender, EventArgs e)
    {
        // 输入有效性校验
        if (!int.TryParse(MonthInput.Text, out int totalMonths) || 
            !int.TryParse(IncomeInput.Text, out int baseIncome))
        {
            // 可添加提示逻辑,比如弹窗告知输入无效
            return;
        }

        MonthlyIncomeCalculus = new ObservableCollection<MonthlyIncomeItem>();

        for (int i = 0; i < totalMonths; i++)
        {
            int currentMonth = i + 1;
            decimal calculatedIncome = baseIncome * 1.1m * currentMonth;
            MonthlyIncomeCalculus.Add(new MonthlyIncomeItem 
            { 
                Month = currentMonth, 
                Income = calculatedIncome 
            });
        }
    }

    // INotifyPropertyChanged 接口实现
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

三、UI可视化实现

方案1:使用第三方DataGrid控件(推荐)

Xamarin/MAUI无原生DataGrid,可使用CommunityToolkit提供的控件:

  1. 安装NuGet包:
    • MAUI项目:CommunityToolkit.Maui
    • Xamarin.Forms项目:Xamarin.CommunityToolkit
  2. 在XAML中添加DataGrid:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="YourAppNamespace.HomePage">
    <StackLayout Padding="20">
        <Entry x:Name="MonthInput" Placeholder="输入月份数" Keyboard="Numeric"/>
        <Entry x:Name="IncomeInput" Placeholder="输入基础收入" Keyboard="Numeric"/>
        <Button Text="计算" Clicked="calculate"/>
        <toolkit:DataGrid ItemsSource="{Binding MonthlyIncomeCalculus}" 
                          AutoGenerateColumns="False"
                          Margin="0,20,0,0">
            <toolkit:DataGrid.Columns>
                <toolkit:DataGridTextColumn Header="Month" Binding="{Binding Month}"/>
                <toolkit:DataGridTextColumn Header="Income" Binding="{Binding Income, StringFormat='{0:C}'}"/>
            </toolkit:DataGrid.Columns>
        </toolkit:DataGrid>
    </StackLayout>
</ContentPage>

方案2:用CollectionView模拟表格(无需第三方库)

如果不想依赖第三方控件,可使用原生CollectionView实现表格效果:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourAppNamespace.HomePage">
    <StackLayout Padding="20">
        <Entry x:Name="MonthInput" Placeholder="输入月份数" Keyboard="Numeric"/>
        <Entry x:Name="IncomeInput" Placeholder="输入基础收入" Keyboard="Numeric"/>
        <Button Text="计算" Clicked="calculate"/>
        
        <CollectionView ItemsSource="{Binding MonthlyIncomeCalculus}" Margin="0,20,0,0">
            <!-- 表头 -->
            <CollectionView.Header>
                <Grid ColumnDefinitions="*,*" BackgroundColor="#f0f0f0">
                    <Label Grid.Column="0" Text="Month" FontAttributes="Bold" Padding="10" HorizontalTextAlignment="Center"/>
                    <Label Grid.Column="1" Text="Income" FontAttributes="Bold" Padding="10" HorizontalTextAlignment="Center"/>
                </Grid>
            </CollectionView.Header>
            <!-- 列表项布局 -->
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid ColumnDefinitions="*,*" BorderColor="#ccc" BorderThickness="0,0,0,1">
                        <Label Grid.Column="0" Text="{Binding Month}" Padding="10" HorizontalTextAlignment="Center"/>
                        <Label Grid.Column="1" Text="{Binding Income, StringFormat='{0:C}'}" Padding="10" HorizontalTextAlignment="Center"/>
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>
</ContentPage>

内容的提问来源于stack exchange,提问作者Kimba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:15:35