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

.NET MAUI CollectionView内元素修改时如何追踪对应数据对象?

.NET MAUI CollectionView 识别修改的数据对象方案

方法1:在数据类的属性Setter中直接处理

  • 让你的数据模型类继承ObservableObject(.NET MAUI官方推荐,已实现INotifyPropertyChanged)
  • 在每个可修改属性的setter里,完成属性更新后直接标记当前对象的修改状态,或者触发自定义事件通知上层ViewModel。

示例代码:

public class YourDataModel : ObservableObject
{
    private bool _isChecked;
    public bool IsChecked
    {
        get => _isChecked;
        set
        {
            if (SetProperty(ref _isChecked, value))
            {
                // 直接标记当前对象已修改
                Modified = true;
                // 也可以触发自定义事件,让ViewModel监听
                OnModified?.Invoke(this, EventArgs.Empty);
            }
        }
    }

    private string _itemText;
    public string ItemText
    {
        get => _itemText;
        set
        {
            if (SetProperty(ref _itemText, value))
            {
                Modified = true;
                OnModified?.Invoke(this, EventArgs.Empty);
            }
        }
    }

    public bool Modified { get; private set; } = false;
    public event EventHandler OnModified;
}

只要UI控件和属性绑定正确,无论用户怎么修改UI,都会触发属性setter,就能直接在对象内部标记修改状态,ViewModel也可通过订阅OnModified事件统一处理。

方法2:通过UI元素的事件绑定命令传递对象

  • 给DataTemplate里的Checkbox、Entry等控件绑定命令,把当前绑定的数据对象作为CommandParameter传递给ViewModel的命令,直接拿到修改的对象。

XAML示例:

<CollectionView ItemsSource="{Binding DataList}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout>
                <Checkbox IsChecked="{Binding IsChecked}" 
                          CheckedChangedCommand="{Binding Source={RelativeSource AncestorType={x:Type local:YourViewModel}}, Path=ItemModifiedCommand}"
                          CheckedChangedCommandParameter="{Binding .}"/>
                <Entry Text="{Binding ItemText}" 
                       TextChangedCommand="{Binding Source={RelativeSource AncestorType={x:Type local:YourViewModel}}, Path=ItemModifiedCommand}"
                       TextChangedCommandParameter="{Binding .}"/>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

ViewModel中的命令实现:

public ICommand ItemModifiedCommand => new Command<YourDataModel>(model =>
{
    // 这里的model就是被修改的目标数据对象
    model.Modified = true;
    // 执行后续逻辑,比如同步修改记录、更新全局状态等
});

这种方式适合在ViewModel层统一处理所有对象的修改事件,避免在数据类中写入过多业务逻辑。

额外说明

CollectionView的ItemSelection事件仅在用户点击Item容器本身(而非内部控件)时触发,内部UI元素的操作不会触发该事件,属于正常行为,无需强行依赖它实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:15:04