2014-07-24 6 views
4

Android에서 버튼 클릭으로 Stacklayout에 라벨보기를 추가하려고했습니다. 하지만 Null 포인터 예외가 발생합니다. 아래는 내가 습득하려는 것입니다. 사람이 ButtonClick에 라벨을 추가버튼에 부모를 추가하십시오. Xamarin.forms를 클릭하십시오.

StackLayout parent= new StackLayout(); 

Button add= new Button 
     { 
      HorizontalOptions=LayoutOptions.End, 
      BackgroundColor=Xamarin.Forms.Color.White, 
      Text="ADD", 
      TextColor=Xamarin.Forms.Color.Maroon, 
     }; 

add.Clicked += OnButtonClicked; 

Label firstLabel = new Label 
     { 
      Text = "Label 1", 
      HorizontalOptions = LayoutOptions.StartAndExpand, 
      TextColor=Xamarin.Forms.Color.FromHex("#000000") 
     }; 
parent.Children.Add(add); 
parent.Children.Add(firstLabel); 

void OnButtonClicked(object sender, EventArgs e) 
{ 

    Label secondLabel = new Label 
     { 
      Text = "Label 1", 
      HorizontalOptions = LayoutOptions.StartAndExpand, 
      TextColor=Xamarin.Forms.Color.FromHex("#000000") 
     }; 
    parent.Children.Add(secondLabel); 
} 

감사합니다 사전

에서 C#으로

Xamarin.Forms 코드 xamarin.forms이를 acheive하는 방법에 대한 조언을 주시겠습니까

+0

: 항상 버전 충돌이 버전은 테스트 및 iOS에서 작동했다

을하지 않는 수행 솔루션 수준에서 패키지를 업데이트합니다. 가져 오는 스택 추적으로 게시물을 편집 할 수 있습니까? –

답변

6

코드가있는 그대로 작동합니다 ... 하나의 작은 변경으로 -을 만드십시오.클래스 필드에서 참조 할 수 있도록 OnButtonClicked

최신 Xamarin.Forms를 갖도록 솔루션 패키지를 업데이트해야합니다. 나는이 실패 할 이유를 볼

public class LabelPage: ContentPage 
    { 
     StackLayout parent = null; 

     public LabelPage() 
     { 
      parent = new StackLayout(); 

      Button add = new Button { 
       HorizontalOptions = LayoutOptions.End, 
       BackgroundColor = Xamarin.Forms.Color.White, 
       Text = "ADD", 
       TextColor = Xamarin.Forms.Color.Maroon, 
      }; 

      add.Clicked += OnButtonClicked; 

      Label firstLabel = new Label { 
       Text = "Label 1", 
       HorizontalOptions = LayoutOptions.StartAndExpand, 
       TextColor = Xamarin.Forms.Color.FromHex ("#000000") 
      }; 
      parent.Children.Add (add); 
      parent.Children.Add (firstLabel); 

      Content = parent; 
     } 

     void OnButtonClicked (object sender, EventArgs e) 
     { 
      Label secondLabel = new Label { 
       Text = "Label 1", 
       HorizontalOptions = LayoutOptions.StartAndExpand, 
       TextColor = Xamarin.Forms.Color.FromHex ("#000000") 
      }; 
      parent.Children.Add (secondLabel); 
      //UpdateChildrenLayout(); 
     } 
    } 
+0

나는 안드로이드에서 노력하고있다. 나는 당신이 제안한 길을 시도했지만 운이 없다. –

+0

어떤 에러가 나고 있니? –

+0

** parent.Children.Add (secondLabel); ** _object 참조가 object_ 오류 –

관련 문제