关于C#:比较带有矩形填充错误的文本前景

comparing text foreground with rectangle fill error

我正在Windows Phone 8中开发棘手的颜色游戏
我有一个文本块和8个矩形(颜色)

任务是按文本的颜色而不是单词的颜色!

示例:如果文本为:红色,并且前景为绿色
播放器必须点击绿色矩形而不是红色矩形

因此在检查答案功能

我写道:

1
2
3
4
5
6
7
8
9
10
private void CheckAnswer(Rectangle c)
        {
            if (SaveMission == 1)
            {
                if (ColorText.Foreground.Equals(c.Fill))
                    MessageBox.Show("Right Answer");
                else
                    MessageBox.Show("Wrong Answer");
            }  
        }

前景属性为Windows.Media.Bursh

,Fill属性也获得Windows.Media.Brush

当我调试应用程序时:答案始终是错误的!
有什么问题吗?


首先是一个示例程序,它将演示该问题

1
2
3
4
5
System.Windows.Media.Brush b1 = new SolidColorBrush(Color.FromArgb(0,0,0,0));
System.Windows.Media.Brush b2 = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));

bool b = b1.Equals(b2);
//b will equal false

现在,如果在程序未运行时用鼠标悬停在.Equals上,则会看到它正在使用DependencyObject.Equals方法,该方法"确定所提供的DependencyObject是否等效于当前DependencyObject"。换句话说,就是不比较颜色

解决方案是投射和检索颜色

1
2
3
4
System.Windows.Media.Brush b1 = new SolidColorBrush(Color.FromArgb(0,0,0,0));
System.Windows.Media.Brush b2 = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));

bool b = ((SolidColorBrush)b1).Color.Equals(((SolidColorBrush)b2).Color);