2011-04-15 186 views
0

我正在开发Windows Phone 7应用程序。将列表框绑定到表

我有一个表有以下栏目:

ID | Name | Description 

我想在ListBox显示所有名称表。我想确定用户何时选择一行并获取其ID。

如何将ID存储在ListBoxItem中?我该如何检索它?

回答

1

假设你有每一行相应的数据对象(我们称之为MyDataRow现在),你的ListBox的的ItemsSource属性设置为您MyDataRow实例的集合。然后,在您的列表框中,将DisplayMemberPath设置为名称。这将使ListBox绑定到您的实际数据对象,但实际显示名称属性的值。

当你处理的SelectionChanged事件的SelectedItem属性的值将是你MyDataRow类的一个实例,所以你可以使用这样的代码获得ID:

var id = ((MyDataRow)_myListBox.SelectedItem).ID;

+0

和..我在哪里可以学习做呢?我只有一个用XML文件创建的数据源。 – VansFannel 2011-04-15 14:59:59

+1

这应该有所帮助:http://www.windowsphonegeek.com/articles/data-binding-the-wp7-listpicker-to-xml-data-using-expressionblend-4 – 2011-04-15 15:04:22

+0

谢谢,它的工作。但我还有一个问题。在该表上我有另一列来表示语言(en,es,...)如何设置ItemsSource的where子句?或者我可以做一个看法? – VansFannel 2011-04-15 15:31:46

1

使用绑定是最好的方法。见我的代码如下:

<ListBox x:Name="List1"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
       </Grid.ColumnDefinitions> 
       <TextBlock Text="{Binding ID}" /> 
       <TextBlock Text="{Binding Name}" Grid.Column="1" /> 
       <TextBlock Text="{Binding Description}" Grid.Column="2" /> 
      </Grid> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

<TextBlock Grid.Row="2" Text="{Binding ElementName=List1,Path=SelectedItem.ID}" /> 

// CSHARP代码:

public partial class MainPage : PhoneApplicationPage 
{ 
    // Constructor 
    public MainPage() 
    { 
     InitializeComponent(); 

     Collection<Entity> source = new Collection<Entity> { 
      new Entity{ID = "1", Name = "Name1", Description = "This is Name1"}, 
      new Entity{ID = "2", Name = "Name2", Description = "This is Name2"}, 
      new Entity{ID = "3", Name = "Name3", Description = "This is Name3"}, 
     }; 

     List1.ItemsSource = source; 
    } 
} 

public class Entity 
{ 
    public string ID { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; } 
}