2013-01-02 28 views
1

我想在按鈕2的點擊事件中改變button1的內容。但無法獲取列表<> 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 
       } 
      }; 

    } 

} 
+0

'objButton1.Content =「SomthingElse」'不工作嗎? –

+0

它確實有效,但如果您的對象是在運行系統中構建的,那麼如何訪問該對象。 – Sonu

+1

然後在您的類中創建一個字段,並在創建它時存儲該按鈕? – Joey

回答

2

假設你不能只是保持一個參考創建的控制,比如在一個類字段,您可以通過GridChildren財產迭代,並找到所需的按鈕。如果有多個按鈕,您可以使用Tag屬性來區分它們。

找到它後,使用Content屬性更改該按鈕的內容,如上面的內容所述。

相關問題