Question

I try to view items in ScrollViewer but it display nothing

There is Xaml:

<ScrollViewer>
    <ItemsControl ItemsSource="{Binding myList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Text}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ScrollViewer>

Ok. I make some changes in c# cod but it still does not work:

public class MyItem
{
    string text;
    public string Text
        {
            set { text = value;  }
            get { return text; }
        }
}
public partial class MainPage : PhoneApplicationPage
{
    public ObservableCollection<MyItem> myList { get; set; }

    public MainPage()
    {
        myList = new ObservableCollection<MyItem>();

        myList.Add(new MyItem() { Text = "Abkhazia" });
        myList.Add(new MyItem() { Text = "Afghanistan" });
        myList.Add(new MyItem() { Text = "Albania" }); 

        InitializeComponent();
    }
}
Was it helpful?

Solution

A few reasons:

  1. Your observablecollection needs to be public.
  2. Your observablecollection should be a property.

    public class MyClass {

    public ObservableCollection<MyItem> myList {get; set;}
    
    
    public MyClass()
    {
    
        DataContext=this;
        myList = new ObservableCollection();
    
        myList.Add(new MyItem() { Text = "Abkhazia" });
        myList.Add(new MyItem() { Text = "Afghanistan" });
        myList.Add(new MyItem() { Text = "Albania" });
    }
    

    }

Also keep in mind if your modifying "MyItem" it needs to support INotifyPropertyChanged or your display will NOT update.

OTHER TIPS

You should define ItemTemplate properly:

<ScrollViewer>
    <ItemsControl ItemsSource="{Binding myList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Text}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ScrollViewer>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top