简体   繁体   English

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

[英]How to compare if((sender as Grid).Background== new SolidColorBrush(Colors.Green)) in wpf

How to compare if((sender as Grid).Background== new SolidColorBrush(Colors.Green)) in wpf 如何在WPF中比较if((sender as Grid).Background == new SolidColorBrush(Colors.Green))
grid is dynamic 网格是动态的

below is code 下面是代码

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 shows null value co显示空值

You should not compare two different brushes, instead, get both colors and compare them: 您不应该比较两种不同的笔刷,而要同时获得两种颜色并进行比较:

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

Your code implies that you are not using MVVM as pattern. 您的代码表明您没有将MVVM用作模式。 WPF was meant to be programmed using the MVVM pattern. WPF打算使用MVVM模式进行编程。 You may want to look it up and use it, it makes things a lot easier. 您可能需要查找并使用它,这使事情变得容易得多。

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

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