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

.NET MAUI:获取DataGrid内Entry值及关联对应产品的方法

.NET MAUI DataGrid中Entry输入值获取方案

不需要单独维护ObservableCollection<string>,直接将Entry的输入值绑定到Product实体的对应属性上,就能天然解决“输入值与产品关联”的问题,具体实现步骤如下:


1. 扩展Product实体类

为Product添加用于绑定输入值的属性,确保实现属性变更通知(推荐使用CommunityToolkit.Mvvm的ObservableObject基类简化实现):

public partial class Product : ObservableObject
{
    public int Id { get; set; }
    public string ProductName { get; set; }

    // 绑定"Quantity per unit"的输入值
    [ObservableProperty]
    string quantityPerUnit;

    // 绑定"Quantity per Package"的输入值
    [ObservableProperty]
    string quantityPerPackage;
}

2. 修改XAML中的Entry绑定

将两个Entry的Text属性设置为双向绑定,关联到Product的对应属性:

<dg:DataGridColumn Title="Quantity per unit">
    <dg:DataGridColumn.CellTemplate>
        <DataTemplate>
            <Entry TextColor="White"
                   FontSize="18"
                   HorizontalTextAlignment="Center"
                   Text="{Binding QuantityPerUnit, Mode=TwoWay}"/>
        </DataTemplate>
    </dg:DataGridColumn.CellTemplate>
</dg:DataGridColumn>
<dg:DataGridColumn Title="Quantity per Package">
    <dg:DataGridColumn.CellTemplate>
        <DataTemplate>
            <Entry TextColor="White"
                   FontSize="18"
                   HorizontalTextAlignment="Center"
                   Text="{Binding QuantityPerPackage, Mode=TwoWay}"/>
        </DataTemplate>
    </dg:DataGridColumn.CellTemplate>
</dg:DataGridColumn>

3. 在ViewModel中获取关联的输入值

点击按钮时,直接遍历Products集合即可获取每个产品对应的输入值,无需额外处理关联关系:

[RelayCommand]
public async Task ShowValues()
{
    // 遍历所有产品,输出测试信息
    foreach (var product in Products)
    {
        await Shell.Current.DisplayAlert("产品输入值",
            $"ID: {product.Id}\n名称: {product.ProductName}\n单位数量: {product.QuantityPerUnit}\n包装数量: {product.QuantityPerPackage}",
            "确定");
    }

    // 如需批量处理,可整理为结构化数据
    var orderItems = Products.Select(p => new
    {
        ProductId = p.Id,
        ProductName = p.ProductName,
        QuantityPerUnit = p.QuantityPerUnit,
        QuantityPerPackage = p.QuantityPerPackage
    }).ToList();

    // 后续可对orderItems进行测试或提交操作
}

关键说明

  • 绑定到Product实体属性是最直接的方案,既保证了输入值与产品的天然关联,又通过双向绑定实现了UI与数据的实时同步。
  • 必须确保Product类实现INotifyPropertyChanged(使用ObservableObject基类可自动处理),否则输入值变更无法同步到ViewModel。

内容的提问来源于stack exchange,提问作者Yassine El mesbahy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:20:35