-2

So I'm making an application where the user can use the sliders to change the background colour. Here is what I have tried:

private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    Window1.Background = new SolidColorBrush(Color.FromArgb(0, Slider1.Value, Slider2.Value, Slider3.Value));
}

But instead what happens is this:

Error CS1503 Argument 2: cannot convert from 'double' to 'byte'

Error CS1503 Argument 3: cannot convert from 'double' to 'byte'

Error CS1503 Argument 4: cannot convert from 'double' to 'byte'

I tried converting them to byte:

Window1.Background = new SolidColorBrush(Color.FromArgb(0, Convert.ToByte(Slider1.Value), Convert.ToByte(Slider2.Value), Convert.ToByte(Slider3.Value)));

But instead it breaks

NullReferenceException: Object reference not set to an instance of an object.

  • 1
    Can you be more specific about the error you get with the second attempt? – Lies Feb 21 '22 at 06:54
  • 1
    "it breaks" - what does this mean? – Klaus Gütter Feb 21 '22 at 07:14
  • 1
    The error message is clear. `Slider.Value` is a `double`, but `FromArgb` expects four `byte` arguments. This means you would have to cast: `(byte)Silder1.Value`. Make sure the Silder's Maximum is set to 255. Also pass 255 instead of 0 as the first argument, otherwise the Brush will be transparent. – Clemens Feb 21 '22 at 07:19
  • @KlausGütter sorry to mention that, I have included an image link now, you can see – aHappyConstant Feb 22 '22 at 05:42
  • @Clemens the slider's maximum is already set to 255 – aHappyConstant Feb 22 '22 at 05:44
  • @Lies I have included an image, you can see it now (i dont have enough reputation to embed it) – aHappyConstant Feb 22 '22 at 05:45
  • But you would have been able to post the exception text. – Klaus Gütter Feb 22 '22 at 06:57
  • Put a breakpoint on the code line `Window1.Background = ...` and check whether `Slider1`, `Slider2`, `Slider3`, and `Window1` are all non-null. – Klaus Gütter Feb 22 '22 at 06:58
  • The ValueChanged event is raised before the Slider1/2/3 members are initialized. Check them for null like `if (Slider1 != null && Slider2 != null && Slider3 != null) { ... }` – Clemens Feb 22 '22 at 07:08

1 Answers1

0

First make sure that the value you want to convert is between (0 - 255), by setting the Slider's Maximum to 255.

Then try

new SolidColorBrush(Color.FromArgb(
    255, (byte)Slider1.Value, (byte)Slider2.Value, (byte)Slider3.Value));
Clemens
  • 123,504
  • 12
  • 155
  • 268
Omid Sn
  • 34
  • 3
  • Actually what happened at that time the sliders were null. So, I had to add the code suggested by @Clemens so that the code would not execute if the sliders were null. – aHappyConstant Feb 22 '22 at 11:22