数据绑定到Gridview

时间:2014-08-19 04:26:30

标签: c# gridview windows-phone-8.1

当我尝试将数据绑定到GridView时,它什么也没显示。

以下是我所指的代码:

<Grid>
    <GridView x:Name="gridview" 
              ItemsSource="{Binding Pictures}">
        <GridView.ItemTemplate>
            <DataTemplate x:Name="GridviewItemTemplate">
                <Grid>
                    <Image Source="{Binding ImageUri}" Height="250" Width="250" />
                    <TextBlock Text="{Binding LocationName}"   HorizontalAlignment="Right"
                                           VerticalAlignment="Bottom" FontSize="12" />
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</Grid>

这是代码背后的代码

public MainPage()
{
    this.InitializeComponent();
}

public IEnumerable<LocationPicture> Pictures
{
    get { return _pictures; }
    set { _pictures = value; }
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    CreateDummyList();
}

public void CreateDummyList()
{
    List<LocationPicture> pictures = new List<LocationPicture>();
    pictures.Add(new LocationPicture { 
                     ImageUri = "Images/1.jpg", 
                     LocationName = "location" 
                 });
    pictures.Add(new LocationPicture { 
                     ImageUri = "Images/2.jpg", 
                     LocationName = "location" 
                 });
    pictures.Add(new LocationPicture { 
                     ImageUri = "Images/3.jpg", 
                     LocationName = "location" 
                 });
    _pictures = pictures;
}

我刚刚为GridView创建了一个虚拟列表,并在onNavigatedTo中调用该方法。

但它在GridView上没有显示任何内容。

1 个答案:

答案 0 :(得分:0)

我相信你应该做到以下几点:

public MainPage()
{
    this.InitializeComponent();
}

public ObservableCollection<LocationPicture> Pictures
{
    get { return _pictures; }
    set { _pictures = value; }
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    CreateDummyList();
}

public void CreateDummyList()
{
    List<LocationPicture> pictures = new ObservableCollection<LocationPicture>();
    pictures.Add(new LocationPicture { ImageUri = "Images/1.jpg", LocationName = "location" });
    pictures.Add(new LocationPicture { ImageUri = "Images/2.jpg", LocationName = "location" });
    pictures.Add(new LocationPicture { ImageUri = "Images/3.jpg", LocationName = "location" });

    _pictures = pictures;       
    this.DataContext = this;
}

但最好将您的集合移动到ViewModel类并将DataContext绑定到它。在MVVM guide

中查看更多相关信息