简体   繁体   English

比较颜色WPF

[英]Compare Colors WPF

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. 但问题是总是处于else状态。 Even if the colors is the same in the if condition it returns me false . 即使if条件中的颜色相同,它if返回false And always when clicked my ellipse turns gray. 并且总是在点击时我的椭圆变成灰色。

Why this is happening? 为什么会这样? How can I fix? 我该怎么办?

EDIT: 编辑: 这个<code> if </ code>返回false

You're probably comparing different brush instances, which is why the if statement returns false. 您可能正在比较不同的画笔实例,这就是if语句返回false的原因。 You can compare just the color instead: 你可以只比较颜色:

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

Do not create your own SolidColorBrush instances, but use the predefined ones from the Brushes class: 不要创建自己的SolidColorBrush实例,而是使用Brushes类中的预定义实例:

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;
}

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. obj.Stroke的值显然不是new SolidColorBrush(Colors.Red) ......它可能Brushes.Red ,或Brushes.Green等,但这只是猜测。 You can find out for sure by simply putting a break point on your if statement. 您可以通过简单地在if语句上添加一个断点来确定。

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. 将鼠标光标移动到Visual Studio中的obj.Stroke上(当命中断点时)将告诉您确切的值是什么,然后您可以在if语句中使用值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM