【问题标题】:Two-way data binding in AdaptiveGridViewAdaptiveGridView 中的双向数据绑定
【发布时间】:2019-06-03 17:17:54
【问题描述】:

我正在创建一个 UWP 应用,我在其中使用 AdaptiveGridView 控件来显示项目列表。

当我第一次设置 AdaptiveGridView 的 ItemsSource 时,一切都按预期工作,我看到了呈现的列表。

但是,如果我尝试将新项目添加到 AdaptiveGridView 的 ItemsSource 属性,则该新项目不会显示。但是在查看 ItemsSource 时,我可以看到确实添加了新项目,但它没有显示出来。

我尝试过的唯一解决方法是首先将 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;
    }

当我添加新项目时应该显示它们,但它们没有,我不得不这样做

【问题讨论】:

    标签: c# xaml uwp


    【解决方案1】:

    List类没有实现INotifyPropertyChanged Interface ,当有新的item添加进去时,会通知UI。

    要解决您的问题,请使用ObservableCollection

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多