简体   繁体   English

当 ObservableCollection 中的 object 属性发生变化时,通知另一个属性 CommunityToolkit Mvvm

[英]When object property in ObservableCollection changed, notify another property, CommunityToolkit Mvvm

Class definition: Class 定义:

    public partial class Pozycje: ObservableObject
    {
        [ObservableProperty] private bool _ok;
        [ObservableProperty] private string _name;
        [ObservableProperty] private decimal _qty;
        [ObservableProperty] private decimal _val;
    }

Collection and property definition:集合和属性定义:

public decimal Suma => Pozycja.Where(x => x.Ok).Sum(x=>x.Val+x.Qty);

private ObservableCollection<Pozycje> _poz;
public ObservableCollection<PozycjaObservable> Poz
{
    get => _poz;
    set
    {
      _poz = value;
      OnPropertyChanged();
      OnPropertyChanged(nameof(Suma));
   }
}

In Xaml:在 Xaml 中:

 <Label Text="{Binding Suma}"/>

When I change "Poz" collection item property "Ok" Suma don't update.当我更改“Poz”收集项目属性“Ok”时,Suma 不会更新。

Poz s setter is only called when Poz is assigned, NOT when items are added/removed Poz的 setter 仅在分配Poz时调用,而不是在添加/删除项目时调用

if you want to update Suma when an item is added or removed from Poz , you need to use Poz s CollectionChanged event如果要在Poz添加或删除项目时更新Suma ,则需要使用PozCollectionChanged事件

Poz.CollectionChanged += {
  OnPropertyChanged(nameof(Suma));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM