如何在wpf中比较if((sender as Grid).Background == new SolidColorBrush(Colors.Green))

时间:2014-08-11 06:03:37

标签: c# wpf colors

如何在wpf中比较if((发送者为网格).Background == new SolidColorBrush(Colors.Green)) 网格是动态的

下面是代码

private void Grid_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {

            System.Windows.Media.Brush newColor = System.Windows.Media.Brushes.Yellow;
            // SolidColorBrush newBrush = (SolidColorBrush)newColor;

            //   //  System.Drawing.Brush b = new System.Drawing.SolidBrush((System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString(new System.Windows.Media.BrushConverter().ConvertToString(Colors.Yellow)));
            //// System.Windows.Media.Color imageColor =( System.Windows.Media.Color) newBrush;
            string co = null;

            if((sender as Grid).Background== new SolidColorBrush(Colors.Green))

                co = "Audited";
            else if((sender as Grid).Background== new SolidColorBrush(Colors.Red))
                co = "DoNotAudit";
            else if((sender as Grid).Background== new SolidColorBrush(Colors.Orange))
                co = "ReAudit";
            else if((sender as Grid).Background== new SolidColorBrush(Colors.Yellow))
                co = "TobeAudited";
            MessageBox.Show(co);
        }


    }

co显示空值

1 个答案:

答案 0 :(得分:5)

你不应该比较两种不同的画笔,而是获得两种颜色并进行比较:

var grid = sender as Grid;

if(grid != null)
{
  var background = grid.Background as SolidColorBrush;

  if(background != null)
  {
    var color = background.Color;

    if(Colors.Green.Equals(color))
    {
       co = "Audited";
    }
    else if(Colors.Red.Equals(color))
    {
      co = "DoNotAudit";
    }
    else if(Colors.Orange.Equals(color))
    {
      co = "ReAudit";
    }
    else if(Colors.Yellow.Equals(color))
    {
      co = "TobeAudited";
    }
  }
}

您的代码暗示您没有使用MVVM作为模式。 WPF旨在使用MVVM模式进行编程。你可能想要查找并使用它,它会让事情变得更容易。