Windows Phone:用c#命令添加XAML标签

本文关键字:添加 XAML 标签 命令 Phone Windows | 更新日期: 2023-09-27 18:10:43

Windows Phone 8 App (c#):

  • 我有一个数组与人的名字,姓氏和员工编号。
  • 这个数组没有固定长度
  • 在XAML,我试图显示所有人的名字的列表,链接到一个页面,我们需要他们的员工编号。

现在,有没有人有一个想法,如果有可能只添加尽可能多的XAML TextBlocks作为数组长度?

它们看起来像这样:

<TextBlock x:Name="first" Text=""  HorizontalAlignment="Left" Margin="0,(*X*+50),0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="50" Width="445"/>

开始开发这个应用程序的女孩只是放了30个textblock标签,并使用了许多if语句来填充这些,如果这些数据可用的话。这是唯一可能的解决方案吗?(

非常感谢你的帮助!亲切的问候,丽贝卡

Windows Phone:用c#命令添加XAML标签

Xaml Code

   <ListBox x:Name="lstbx">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding FirstName}" Foreground="Red"></TextBlock>
            <TextBlock Text="{Binding LastName}" Foreground="Green"></TextBlock>
            <TextBlock Text="{Binding EmployeeNumber}" Foreground="Blue"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

c#代码

public class Person
{
    public string  FirstName { get; set; }
    public string  LastName { get; set; }
    public int EmployeeNumber { get; set; }
    public Person(string FirstName, string LastName, int EmployeeNumber)
    {
        this.FirstName = FirstName;
        this.LastName = LastName;
        this.EmployeeNumber = EmployeeNumber;
    }
}
       protected override void OnNavigatedTo(NavigationEventArgs e)
    {      
        var data = new Person[]
       {
           new Person("Fistname1","LastName1",1),
           new Person("Fistname2","LastName2",2),
           new Person("Fistname3","LastName3",3),
           new Person("Fistname4","LastName4",4),
       };
        lstbx.ItemsSource = data;
    }

您可以简单地使用这样的循环 foreach(string s in ArrayName) { TextBlock TB = new Textblock(); // set all the properties of the textblock like TB.width= SOMEVALUE; TB.height=SOMEVALUE; ..... ..... ..... ..... // once you are done // just put that Textblock as a child of the wrapper //say you have a grid wrapping all your textboxes , then GRID.children.add(TB);

}

是的,您可以在代码中使用for循环为数组中的每个项目创建一个新的文本块。您最好使用List<T>或可观察集合,因为它们比数组更容易迭代。

代码应该是这样的:

 foreach (string item in myList)
        {
          var tb = new TextBlock();
              tb.Text = item
        }

这是伪代码但希望你们能明白