简体   繁体   中英

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

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. WPF was meant to be programmed using the MVVM pattern. You may want to look it up and use it, it makes things a lot easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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