1

我想在 button2 的点击事件上更改 button1 的内容。但无法获取 List<> UiList 中网格的子 Button 类的对象。 请指导我找到正确的方法来查看和解决它。并且还指导如果对象是在运行时构建的,那么如何访问它?

public partial class MainPage :   PhoneApplicationPage

  {  

    List<Grid> UIList = new List<Grid>();
    Grid objGrid1 = null;
    Button objButton1 = null;
    Button objButton2 = null;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        createGrid1("grid1");
        createButton2("Button2");
    }


    public void createGrid1(string x)
    {
        objGrid1 = new Grid();
        objGrid1.Height = 100;
        objGrid1.Name = x;
        objGrid1.Width = 200;
        objGrid1.Margin = new Thickness(100, 100, 0, 0);
        objGrid1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        objGrid1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        objGrid1.Background = new SolidColorBrush(Colors.Orange);            
        createButton1("changename");

    }
    public void createButton1(string _name)
    {
        objButton1 = new Button();
        objButton1.Height = 90;
        objButton1.Name = _name;
        objButton1.Content="Button1";
        objButton1.FontSize = 20;
        objButton1.Width = 190;            
        objButton1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        objButton1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        objButton1.Background = new SolidColorBrush(Colors.Blue);
        objButton1.Foreground = new SolidColorBrush(Colors.White);
        objGrid1.Children.Add(objButton1);
        LayoutRoot.Children.Add(objGrid1);
        UIList.Add(objGrid1);

    }
    public void createButton2(string _name)
    {
        objButton2 = new Button();
        objButton2.Margin = new Thickness(240, 300, 0, 0);
        objButton2.Name = _name;
        objButton2.Height = 90;
        objButton2.Content = "Button2";
        objButton2.FontSize = 20;
        objButton2.Width = 190;
        objButton2.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        objButton2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        objButton2.Background = new SolidColorBrush(Colors.Blue);
        objButton2.Foreground = new SolidColorBrush(Colors.White);
        LayoutRoot.Children.Add(objButton2);
        objButton2.Click += (s, e) =>
            {
                int c = UIList.ElementAt(0).Children.Count;
                if (c == 1)
                {
                    //logic to change content of Button1 on click of Button2
                }
            };

    }

}
4

1 回答 1

2

假设您不能只保留对已创建控件的引用,例如在类字段中,您可以遍历Grid的Children属性并找到所需的 Button。如果有多个按钮,您可以使用Tag属性来区分它们。

找到它后,使用Content属性更改按钮的内容,如上面的内容中所述。

于 2013-01-02T07:53:42.023 回答