I have some ellipsis in a canvas. I want that when I click above a ellipse it should change the color of the stroke to green, and if I click again it back to the original color that its red.

I had used this three colors.

SolidColorBrush red = new SolidColorBrush(Colors.Red);
SolidColorBrush green = new SolidColorBrush(Colors.Green);
SolidColorBrush transp = new SolidColorBrush(Colors.Transparent);

When I create the ellipse I already set the colors as red.

Ellipse obj = new Ellipse()
{
    Name = "",
    Width = width,
    Height = height,
    Fill = transp,
    Stroke = red,
};

Then if I click in some ellipse I ask the stroke color to change color.

if (obj.Stroke == red) obj.Stroke = green;
else if (obj.Stroke == green) obj.Stroke = red;
else obj.Stroke = gray;

But the problem is that always get in else condition. Even if the colors is the same in the if condition it returns me false. And always when clicked my ellipse turns gray.

Why this is happening? How can I fix?

EDIT: this <code>if</code> returns me false

有帮助吗?

解决方案

Do not create your own SolidColorBrush instances, but use the predefined ones from the Brushes class:

Ellipse obj = new Ellipse()
{
    Name = "",
    Width = width,
    Height = height,
    Fill = Brushes.Transparent,
    Stroke = Brushes.Red,
};

...

if (obj.Stroke == Brushes.Red)
{
    obj.Stroke = Brushes.Green;
}
else if (obj.Stroke == Brushes.Green)
{
    obj.Stroke = Brushes.Red;
}
else
{
    obj.Stroke = Brushes.Gray;
}

其他提示

You're probably comparing different brush instances, which is why the if statement returns false. You can compare just the color instead:

if (((SolidColorBrush)obj.Stroke).Color == Colors.Red)
{
    ...
}

The value of obj.Stroke is clearly not new SolidColorBrush(Colors.Red)... it might be Brushes.Red, or Brushes.Green, etc., but that's just a guess. You can find out for sure by simply putting a break point on your if statement.

Moving your mouse cursor over obj.Stroke in Visual Studio (when the break point has been hit) will tell you exactly what the value is and then you can simply use that value in your if statement.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top