C#在ListboxItems内容中传递StringBuilder

时间:2013-07-10 08:28:51

标签: c# listbox type-conversion stringbuilder

我有一个listbox,其中每行传递5个项目。我的XML文件如下所示:

 <ListBox x:Name="DatabaseBox" ItemsSource="{Binding Book}">
     <ListBox.ItemTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal" Width="auto" Height="22">
             <Image x:Name="ToggleFavoriteImage" Width="10" Height="10" Tag="{Binding Tag}" Source="{Binding ImageSource}" HorizontalAlignment="Center"/>
                <TextBlock Text="{Binding Name}" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Center"/>
                <ListBoxItem Content="{Binding City}" HorizontalAlignment="Center"/>
                <ListBoxItem Content="{Binding Author}" HorizontalAlignment="Center"/>
                <ListBoxItem Content="{Binding Country}" HorizontalAlignment="Center"/>
          </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
 </ListBox>

其中Bookprivate static List<BookItems> Book{ get; set; }BookItems

    public struct BookItems
    {
        public string Name{ get; set; }
        public string Url { get; set; }
        public string Author{ get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Tag { get; set; }
        public ImageSource ImageSource { get; set; }
    }

我想要传递到ListBox的所有数据都存储在另一个List中:private static List<Tuple<StringBuilder , StringBuilder , StringBuilder , StringBuilder , StringBuilder >> BookList = new List<Tuple<StringBuilder , StringBuilder , StringBuilder , StringBuilder , StringBuilder >>();

因此,如果我尝试以这种方式填充ListBox

 foreach(var ListItem in BookList)
 {
    Book= new List<BookItems>() 
    {
      new BookItems() 
      {
         Tag = ListItem.Item1.ToString(),ImageSource = FavoriteSource, Name= ListItem.Item1.ToString(), Author= ListItem.Item3.ToString(), City = ListItem.Item4.ToString(),Country = ListItem.Item5.ToString()
       }
     };
     DatabaseBox.Items.Add(Book);
 }

然后我到处都是null,除了图像。如果我将BookList更改为strings和我的书,那么一切顺利,没有任何问题。我每次使用控制台输出和我的StringBuilderstringstrings的转换都为空时检查我的StringBuilder是否正常。我做错了吗?

2 个答案:

答案 0 :(得分:0)

您应该为元组中的StringBuilder项创建实例,如新的StringBuilder()

答案 1 :(得分:0)

正如你所说,stringBuilder很好,所以我的解决方案首先不要为每个项目创建一个列表。我不知道你为什么要这样做但是你不应该为你添加到DatabaseBox的每个项目都列出一个列表。

第二,拿你的代码

Book= new List<BookItems>() 
{
  new BookItems() 
  {
     Tag = ListItem.Item1.ToString(),ImageSource = FavoriteSource, Name= ListItem.Item1.ToString(), Author= ListItem.Item3.ToString(), City = ListItem.Item4.ToString(),Country = ListItem.Item5.ToString()
   }
 };

并重写它。还要重写BookItems中的属性并使其成为一个类。 完成所有这些后,调试过程将很容易。如果stringBuilders包含数据,您将确切地看到它发生了什么。