如果按钮是网格的子项,如何更改按钮的内容

本文关键字:按钮 何更改 网格 如果 | 更新日期: 2023-09-27 17:50:17

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

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

如果按钮是网格的子项,如何更改按钮的内容

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

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