【问题标题】:Data binding / populate items in listbox in windows phone数据绑定/填充 Windows Phone 列表框中的项目
【发布时间】:2012-08-22 04:33:21
【问题描述】:

我有两个单独的类,即:

    public class Floor { 
     private string fname;
   public Floor(string name)
   {
     fname = name;
   }

   public int FName
   {
      set { fname = value; }
      get { return fname; }
   }

}

public class Building 
{
   List<Floor> floors;
   string _bName;

   public Building(string bname)
   {

       _bName = bname;

      floors = new List<Floors>();

      for(int i = 0; i < 3; i++)
      {
           floors.Add(new Floor("floor" + (i + 1)));
      }
   }

   public string BName
   {
      set{ _bName = value; }
      get{ return _bName; }
   }

   public List<Floor> Floors
   {
      set { floors = value; }
      get { return floors; }
   }

}

在我的 XAML (MainPage.xaml) 中:

<ListBox x:Name="lstBuilding" Background="White" Foreground="Black">
  <ListBox.ItemTemplate>
    <DataTemplate>
       <StackPanel Orientation="Horizontal" Margin="10,0,0,15">                  
           <StackPanel>
             <TextBlock Text="{Binding Path=BName }" />                                                                                      
            </StackPanel>
        </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

在我的 XAML.cs (MainPage.xaml.cs) 中

ObservableCollection< Building > buildings = new ObservableCollection< Building>();

for(int i = 0; i < 2; i++)
{
    buildings.Add(new Building("building" + (i + 1)));
}

lstBuilding.ItemsSource = buildings

问题来了:

如何使用 XAML 访问 Floor 类中的 FName? 我所做的是:

<TextBlock Text="{Binding Path=Floors.FName }" />  

但它没有用。 :(

抱歉,帖子太长了。

【问题讨论】:

    标签: data-binding listbox windows-phone


    【解决方案1】:

    您的代码本身存在缺陷,因为您尝试访问 Floors,它又是一个 Collection/List,当您有 &lt;TextBlock Text="{Binding Path=Floors.FName }" /&gt; 时,不清楚您指的是哪个楼层或您要做什么?

    如果只想参考一楼可以试试&lt;TextBlock Text="{Binding Path=Floors[0].FName }" /&gt;

    但如果您尝试访问每个建筑物中每个楼层的数据,则需要更改 xaml 才能使其正常工作。它称为嵌套绑定。

     <ListBox x:Name="listBuilding">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <ListBox ItemsSource="{Binding Floors}">
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding Path=FName}"></TextBlock>
                                    </DataTemplate>
                                </ListBox.ItemTemplate>
                            </ListBox>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多