简体   繁体   English

AdaptiveGridView中的双向数据绑定

[英]Two-way data binding in AdaptiveGridView

I'm create a UWP app where I'm using the AdaptiveGridView control to display a list of items. 我正在创建一个UWP应用程序,我正在使用AdaptiveGridView控件来显示项目列表。

When I first set the ItemsSource of the AdaptiveGridView everything works as expected and I see the list rendered. 当我第一次设置AdaptiveGridView的ItemsSource时,一切都按预期工作,我看到呈现的列表。

However if I try to add a new item to the ItemsSource property of the AdaptiveGridView, that new item does not show up. 但是,如果我尝试将新项添加到AdaptiveGridView的ItemsSource属性,则该新项不会显示。 But when inspecting the ItemsSource, I can see that the new item was indeed added, but it does not show up. 但是在检查ItemsSource时,我可以看到确实添加了新项目,但它没有显示出来。

The only way around this that i've tried was first to set the ItemsSource property to null, then set it again with the new item. 我试过的唯一方法是首先将ItemsSource属性设置为null,然后使用新项目再次设置它。

<Page.Resources>
    <DataTemplate x:Key="Items">
        <Grid Name="GoalCardGrid">
            <!--UI stuff-->
        </Grid>
    </DataTemplate>
</Page.Resources>
<StackPanel Margin="10,0,10,0">
    <UI:AdaptiveGridView Margin="0,20,0,0" HorizontalAlignment="Stretch" Grid.Row="2" x:Name="ItemsGV" 
                         ItemHeight="250" DesiredWidth="700" ItemTemplate="{StaticResource Items}">
    </UI:AdaptiveGridView>
</StackPanel>

    public static List<Item> Items = new List<Item>();

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        Items.Add(new Item()
        {
            ImageUrl = "ms-appx:///Assets/download (1).jpeg"
        });

        Items.Add(new Item()
        {
            ImageUrl = "ms-appx:///Assets/download (2).jpeg"
        });

        ItemsGV.ItemsSource = Items;
    }

    private void AddGoalBtn_Click(object sender, RoutedEventArgs e)
    {
        Items.Add(new Item()
        {
            ImageUrl = "ms-appx:///Assets/download (1).jpeg"
        });
        ItemsGV.ItemsSource = null;
        ItemsGV.ItemsSource = Items;
    }

New items should be displayed when I add them, however they don't and I had to 我添加它们时应该显示新项目,但是我们不必这样做

The List class has not implemented the INotifyPropertyChanged Interface , when the new items are add in it, it will notify the UI. List类没有实现INotifyPropertyChanged接口 ,当新项添加到其中时,它将通知UI。

To solve your issue, please use the ObservableCollection . 要解决您的问题,请使用ObservableCollection

using System.Collections.ObjectModel;
public static ObservableCollection<Item> Items = new ObservableCollection<Item>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM