wpf从包装面板中找到一个按钮

时间:2012-12-25 06:33:27

标签: c# wpf button mouseevent wrappanel

我在Buttons中有WrapPanel,这些是动态创建的。我想更改Button上特定Click_event的高度/宽度。

以下是我在做的事情:

    for (int i = 1; i <= count; i++)
    {
                btn = new Button();
                btn.MinHeight = 22;
                btn.MinWidth = 22;

                btn.Content = i.ToString();
                int _id = id++;
                btn.Name = "btn"+_id.ToString();
                wrpQuestionsMap.Children.Add(btn);

                btn.Click += new RoutedEventHandler(btn_Click);
    }

    private void btnNext_Click_1(object sender, RoutedEventArgs e)
        {
            if (this.view.CurrentPosition < this.view.Count - 1)
            {
                this.view.MoveCurrentToNext();

                Button b = (Button)this.wrpQuestionsMap.FindName("btn"+view.CurrentPosition.ToString());
                if (b != null)
                {
                    b.Width = 30;
                }
            }
        }

我已经尝试过,但它已经变为空,不知道为什么。 请帮忙 谢谢

1 个答案:

答案 0 :(得分:1)

如果我理解正确并且您想要更改单击按钮的大小: 对于这行代码:

btn.Click += new RoutedEventHandler(btn_Click);

你应该有这样的方法:

void btn_Click(object sender, RoutedEventArgs e)
{
  Button btn=(Button)sender; // this is the clicked Button
  btn.Width=30.0;            //changes its Width
}

修改

foreach (Button btn in wrpQuestionsMap.Children)
{
    string name= btn.Content.ToString();
    if  (name == "yourName")   // yourName is the name you are searching for
    {
         btn.Width = 30.0   //change size
         break;             // no need to search more
    }
}

编辑2: 从您问题中的代码来看,您的按钮的内容似乎是一个数字btn.Content = i.ToString();。您在评论中说view.CurrentPosition.ToString()是您当前问题的编号。如果要更改此按钮的宽度,请使用:

foreach (Button btn in wrpQuestionsMap.Children)
{
    string name= btn.Content.ToString(); // it must be a number, check it in the debug, and if it is not, Let me know
    if  (name == view.CurrentPosition.ToString())
    {
         btn.Width = 30.0   //change size
         break;             // no need to search more
    }
}

如果您想更改另一个按钮的宽度,您应该让我知道该按钮中的内容。