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

如何实现WeatherModel更新时联动更新集合内WeatherData的属性?

实现WeatherModel变更时同步更新ObservableCollection内对象的属性

需求

当WeatherModel中的变量(如Temp)发生变化时,更新weatherList(ObservableCollection<WeatherData>)内对象的WeatherTypeData属性,同步最新信息。

现有代码

[ObservableProperty]
private ObservableCollection<WeatherData> weatherList = new ObservableCollection<WeatherData>();

[ObservableProperty]
private WeatherModel weather;

private void GetWeatherList()
{
    WeatherList.Add(new WeatherData()
    {
        WeatherType = "Temperature",
        WeatherTypeData = $"{weather.Temp}°" 
        // 希望weather变化时,能更新这里的WeatherTypeData
    });
}

public partial class WeatherData : ObservableObject
{
    [ObservableProperty]
    private String weatherType;
    [ObservableProperty]
    private String weatherTypeData;
}

public class WeatherModel
{
    public float Temp { get; set; }
    // WeatherModel包含的信息
}

你尝试的代码

[ObservableProperty, NotifyPropertyChangedFor(nameof(WeatherList))]  // 添加了NotifyPropertyChangedFor
private WeatherModel weather;

private void GetWeatherList()
{
    WeatherList.Add(new WeatherData()
    {
        WeatherType = "Temperature",
        WeatherTypeData = $"{Weather.Temp}°" // 同时修改了大小写
    });
}

可行实现方案

你的尝试存在两个核心问题:

  1. NotifyPropertyChangedFor(nameof(WeatherList))无效:它只会通知WeatherList属性本身的变更(比如整个集合被替换),但集合内部元素的属性更新和这个无关。
  2. WeatherModel未实现属性变更通知:Temp变化时,外部无法收到任何信号。

下面是正确的实现步骤:

1. 让WeatherModel实现INotifyPropertyChanged

只有实现这个接口,Temp的变更才能被外部监听:

public class WeatherModel : INotifyPropertyChanged
{
    private float _temp;
    public float Temp
    {
        get => _temp;
        set
        {
            if (_temp != value)
            {
                _temp = value;
                OnPropertyChanged(nameof(Temp));
            }
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

2. 在ViewModel中监听WeatherModel的属性变更

利用CommunityToolkit.Mvvm自动生成的On[PropertyName]Changed部分方法,订阅/取消订阅WeatherModel的PropertyChanged事件:

[ObservableProperty]
private WeatherModel _weather;

// 当Weather属性变更时触发的部分方法(CommunityToolkit.Mvvm自动生成)
partial void OnWeatherChanged(WeatherModel? oldValue, WeatherModel? newValue)
{
    // 取消旧对象的事件订阅,避免内存泄漏
    if (oldValue != null)
    {
        oldValue.PropertyChanged -= WeatherModel_PropertyChanged;
    }
    // 订阅新对象的属性变更事件
    if (newValue != null)
    {
        newValue.PropertyChanged += WeatherModel_PropertyChanged;
        // 初始化时同步一次数据
        UpdateTemperatureItem();
    }
}

private void WeatherModel_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
    // 只处理Temp属性的变更
    if (e.PropertyName == nameof(WeatherModel.Temp))
    {
        UpdateTemperatureItem();
    }
}

private void UpdateTemperatureItem()
{
    // 找到WeatherList中对应类型的项并更新数据
    var tempItem = WeatherList.FirstOrDefault(item => item.WeatherType == "Temperature");
    if (tempItem != null)
    {
        tempItem.WeatherTypeData = $"{Weather.Temp}°";
    }
}

3. 调整初始化逻辑(可选)

为了避免空引用异常,初始化WeatherList时可以加空值判断:

private void GetWeatherList()
{
    WeatherList.Add(new WeatherData()
    {
        WeatherType = "Temperature",
        WeatherTypeData = $"{Weather?.Temp ?? 0}°"
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:07:47