So I have a color picker. Users can pick colors using RGB or HSB. There are sliders/properties for each value. When user sets Red for example, I will calculate HSB values to reflect new color value. When user sets Hue, the RGB value will be recalculated from the HSB values. But see there’s a loop there. When I set RGB it must recalculate HSB values, ok so far, but it also means that HSB values will change causing RGB values to be re updated again. I think this is where the problem is but how can I fix this?
UPDATE: One Possible Solution
One possible solution I used was flag, not very readable tho, but it works. Basically, when I set properties, I also set a flag to signify I am setting a value
public float Hue {
get { return _hue; }
set
{
if (_hue == value)
return;
CurrentlySetting = (CurrentlySetting.HasValue) ? CurrentlySetting : ColorType.HSB;
_hue = value;
NotifyPropertyChanged("Hue");
NotifyPropertyChanged("Color");
RecalculateRGB();
CurrentlySetting = (CurrentlySetting == ColorType.HSB) ? null : CurrentlySetting;
}
}
When I “Recalculate” Values, I check for that and ensure I am not currently setting them
protected void RecalculateRGB(Color color = new Color())
{
if (CurrentlySetting == ColorType.RGB) // prevent stackoverflow
return;
if (color == new Color())
color = HSBColorHelper.FromAHSB(255, Hue, Saturation, Brightness);
Red = color.R;
Green = color.G;
Blue = color.B;
}
Not very straight forward, I still prefer @Marc Gravell’s, solution
I would have all the setters call into the same inner code:
etc – and that inner
SetRGBmethod only talks to the fields (not the properties), including any HSB fields you need; so no recursion. You might also want aSetHSB, obviously – again, setting all the fields (not calling into any of the property setters).