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

如何在WPF中比較if((sender as Grid).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顯示空值

您不應該比較兩種不同的筆刷,而要同時獲得兩種顏色並進行比較:

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模式進行編程。 您可能需要查找並使用它,這使事情變得容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM