Binding ListBox to a table
I'm developing a Windows Phone 7 application.
I have a table with the following columns:
ID | Name | Description
I want to show in a ListBox all names in table. And I want to identify when a user select a row and get开发者_开发知识库 its ID.
How can I store ID inside ListBoxItem? And how can I retrieve it?
Assuming that you have a data object associated with each row (we'll call it MyDataRow
for now), set the ItemsSource property of your ListBox to the collection of your MyDataRow
instances. Then, in your ListBox, set the DisplayMemberPath to Name. This will make the ListBox bind to your actual data objects but actual display the value of the Name property.
When you handle the SelectionChanged event the value of the SelectedItem property will be an instance of your MyDataRow
class, so you can get the ID using code like this:
var id = ((MyDataRow)_myListBox.SelectedItem).ID;
Use binding is the best way. See my code below:
<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 Code:
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; }
}
精彩评论