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

如何使用Community Toolkit的ObservableObject实现关联属性?

正确实现基于Community Toolkit ObservableObject的HSL视图模型

你的尝试未生效,是因为[ObservableProperty]仅自动生成基础的属性访问器和变更通知,没有实现原代码中HSL属性变更触发Color重计算、Color变更同步更新HSL字段的业务逻辑。以下是正确的实现方式:

public partial class HslVM : ObservableObject
{
    [ObservableProperty]
    private float _hue;

    [ObservableProperty]
    private float _saturation;

    [ObservableProperty]
    private float _luminosity;

    [ObservableProperty]
    private Color _color = default!;

    // Hue变更后重新计算Color
    partial void OnHueChanged(float oldValue, float newValue)
    {
        if (oldValue != newValue)
        {
            Color = Color.FromHsla(newValue, Saturation, Luminosity);
        }
    }

    // Saturation变更后重新计算Color
    partial void OnSaturationChanged(float oldValue, float newValue)
    {
        if (oldValue != newValue)
        {
            Color = Color.FromHsla(Hue, newValue, Luminosity);
        }
    }

    // Luminosity变更后重新计算Color
    partial void OnLuminosityChanged(float oldValue, float newValue)
    {
        if (oldValue != newValue)
        {
            Color = Color.FromHsla(Hue, Saturation, newValue);
        }
    }

    // Color变更后同步更新HSL字段并通知变更
    partial void OnColorChanged(Color oldValue, Color newValue)
    {
        if (oldValue == newValue) return;

        var newHue = newValue.GetHue();
        if (_hue != newHue)
        {
            _hue = newHue;
            OnPropertyChanged(nameof(Hue));
        }

        var newSaturation = newValue.GetSaturation();
        if (_saturation != newSaturation)
        {
            _saturation = newSaturation;
            OnPropertyChanged(nameof(Saturation));
        }

        var newLuminosity = newValue.GetLuminosity();
        if (_luminosity != newLuminosity)
        {
            _luminosity = newLuminosity;
            OnPropertyChanged(nameof(Luminosity));
        }
    }
}

关键说明:

  1. [ObservableProperty]的作用:标记私有字段后,工具包会自动生成对应的公共属性(如Hue对应_hue)、属性的setter逻辑,以及基础的PropertyChanged通知。
  2. Partial变更回调:工具包会为每个ObservableProperty生成On<PropertyName>Changed的partial方法,我们可以实现这些方法来添加业务逻辑——这是替代原代码中手动setter逻辑的核心方式。
  3. 避免循环更新:在OnColorChanged中直接更新私有字段(_hue、_saturation、_luminosity)而非公共属性,防止触发HSL属性的变更回调,进而避免循环修改Color。
  4. 变更通知补充:更新私有字段后,手动调用OnPropertyChanged通知对应公共属性的变更,确保UI能同步刷新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:30:51