问题
I am trying to create a ListView of items and to be able to delete them. Here is my code. I can't get the list of items to display. I didn't find a simple example of binding ListViews so i can understand the exact concept. Can you tell me what am i doing wrong ?
PS. myListOfItems is a list with strings. The project is WP 8.1 WinRT.
public class MedClass
{
public string medName { get; set; }
}
public class MedClassRoot
{
public List<MedClass> medNames { get; set; }
}
public sealed partial class MedSavedPage : Page
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
MedClassRoot root = new MedClassRoot();
root.medNames = new List<MedClass>();
foreach (var element in myListOfItems)
{
root.medNames.Add(new MedClass {medName = element});
}
MedSaved_ListView.DataContext = root;
//MedSaved_ListView.ItemsSource = root;
}
<ListView DataContext="{Binding root}"
x:Name="MedSaved_ListView"
HorizontalAlignment="Left"
Height="507"
Margin="10,73,0,0"
VerticalAlignment="Top"
Width="380" Tapped="MedSaved_ListView_Tapped">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Height="30">
<TextBlock Text="{Binding medName}" FontSize="16"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
回答1:
This is the quickest way to get it to work:
Remove the DataContext part from the ListView for now.
Simply set the ItemsSource to the list of your items (comment the part where you do MedSaved_ListView.DataContext = root, and uncomment and alter the next line)
MedSaved_ListView.ItemsSource = root.medNames;
Explanation - the ListView ItemsSource is collection used to generate the content of the ItemsControl. You need to set it to some kind of IEnumerable. Your medNames is of type List which implements IEnumerable so you need to set the ItemsSource to it.
来源:https://stackoverflow.com/questions/28646058/windows-phone-listview-binding