按钮背景图像检查?

时间:2013-07-09 20:17:58

标签: c# winforms button

请尝试检查按钮的背景图像时遇到问题。如果按钮的图像与资源文件夹中的图像匹配,我想删除该按钮。我试过了

    private void DeleteCard(Button btn)
    {
        if (btn.BackgroundImage.Equals( FunWaysInc.Properties.Resources.Card_1))
        {
            playersCards.Remove(Properties.Resources.Card_1);
            MessageBox.Show(playersCards.Count.ToString());
        }
        else
        {
            MessageBox.Show("NO");
        }
    }

    private void frmQuickSpark_Load(object sender, EventArgs e)
    {
        Button tstbtn = new Button();
        tstbtn.BackgroundImage = Properties.Resources.Card_1;
        DeleteCard(tstbtn);
    }

但显示的消息框显示“NO”..

请问发生了什么????

3 个答案:

答案 0 :(得分:1)

添加按钮时

button.Tag = "ToDelete";

然后再

foreach (Button b in this.Controls.OfType<Button>())
{
    if(b.Tag == "ToDelete")
    {
        //delete
    }
}

答案 1 :(得分:0)

这是你要做的。您需要枚举所有图像并将指针存储在按钮的Tag属性中。

private Dictionary<string, Image> _table = new Dictionary<string, Image>();

private void frmQuickSpark_Load(object sender, EventArgs e)
    {
        _table.Add("Image1", Properties.Resources.Card_1);
        _table.Add("Image2", Properties.Resources.Card_2);
        Button btn = new Button();
        SetButtonImage(btn);
        DeleteCard(btn);
    }
 private void SetButtonImage(Button button)
    {

        button.BackgroundImage = _table["Image1"];
        button.BackgroundImage.Tag = "Image1";

    }

    private void DeleteCard(Button btn)
    {
         if (btn.BackgroundImage.Tag == "Image1") 
         {
             playersCards.Remove(btn); // not sure what your logic of removal
             MessageBox.Show(playersCards.Count.ToString());
         }
         else
         {
             MessageBox.Show("NO");
         }
     }

答案 2 :(得分:0)

我已经找到了我的问题的答案..我刚刚修改了我的代码

private void DeleteCard(Image img)
{
    playersCards.Add(Properties.Resources.Card_1);
    if (img == playersCards[0])
    {
        playersCards.Remove(Properties.Resources.Card_1);
        MessageBox.Show(playersCards.Count.ToString());
    }
    else
    {
        MessageBox.Show("NO");
    }
}

private void frmQuickSpark_Load(object sender, EventArgs e)
{
    Button tstbtn = new Button();
    tstbtn.BackgroundImage = Properties.Resources.Card_1;
    Image img = tstbtn.BackgroundImage;
    DeleteCard(img);
}

效果很好。