0

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();
    }
}
4

2 回答 2

1

几个原因:

  1. 你的 observablecollection 需要是公开的。
  2. 你的 observablecollection 应该是一个属性。

    公共类 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" });
    }
    

    }

另外请记住,如果您修改“MyItem”需要支持 INotifyPropertyChanged,否则您的显示将不会更新。

于 2013-09-23T19:56:46.680 回答
0

您应该ItemTemplate正确定义:

<ScrollViewer>
    <ItemsControl ItemsSource="{Binding myList}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Text}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</ScrollViewer>
于 2013-09-23T19:45:24.483 回答