2017-01-01 60 views
0

我在学Xamarin,我知道C#的基础知识。一个我遇到的第一个代码是这是如何工作的?究竟发生了什么?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Xamarin.Forms; 
namespace Hello 
{ 
    public class App : Application 
    { 
    public App() 
     { 
      // The root page of your application 
      MainPage = new ContentPage 
      { 
       Content = new StackLayout 
       { 
        VerticalOptions = LayoutOptions.Center, 
        Children = { 
         new Label { 
          HorizontalTextAlignment = TextAlignment.Center, 
          Text = "Welcome to Xamarin Forms!" 
         } 
        } 
       } 
      }; 
     } 
     protected override void OnStart() 
     { 
      // Handle when your app starts 
     } 
     protected override void OnSleep() 
     { 
      // Handle when your app sleeps 
     } 
     protected override void OnResume() 
     { 
      // Handle when your app resumes 
     } 
    } 
} 

在那里我有一个问题,就是

Children = { 
    new Label { 
     HorizontalTextAlignment = TextAlignment.Center, 
     Text = "Welcome to Xamarin Forms!" 
} 

我不明白发生了什么这里的一部分。什么是Children?它分配给了什么?

+4

儿童StackLayout –

+1

的属性会更加准确,这是从['布局'](https://developer.xamarin.com/继承财产API /属性/ Xamarin.Forms.Layout%3CT%3E.Children /) – UnholySheep

+0

此链接给你不错的主意https://developer.xamarin.com/api/type/Xamarin.Forms.StackLayout/ – Valkyrie

回答

1

Children未分配到,但Children初始化。由于属性“Children”不可浏览,所以它不会出现在intellisense中。

ChildrenIList<View>

可以初始化集合是这样的...

List<string> list = new List<string>{ 
    "s1", 
    "s2", 
    "s3" 
}; 

这相当于

List<string> list = new List<string>(); 
list.Add("s1"); 
list.Add("s2"); 
list.Add("s3"); 

同样

Children = { 
    new Label{ 
    } 
} 

相当于

Children.Add(new Label{ }); 

但是,没有关于如何初始化集合属性的官方文档,但似乎编译器巧妙地转换了表达式。我试图编译,它似乎确实工作正常。

这里你可以看到一个例子,https://dotnetfiddle.net/8jln93

+0

有关官方文档,请参见[link](https:// msdn.microsoft.com/en-us/library/bb384062.aspx)在UnholySheep的评论。 –

+0

大括号内的东西是如何工作的? '新标签Horizo​​ntalTextAlignment = TextAlignment.Center, Text =“欢迎使用Xamarin Forms!” }' –

+0

@PieterWitvoet公文提到如何创建初始化新的对象,而不是如何初始化'IList'财产是只读的,注意它是不是'儿童=新... {',但它是'儿童= {' –