【问题标题】:Refreshing a ListView after an element was added添加元素后刷新 ListView
【发布时间】:2012-04-17 14:12:45
【问题描述】:

我对 Windows 开发很陌生,当然对 Metro 风格的应用程序开发也很陌生。我不确定我是否了解数据绑定的工作原理。

我有一个物品清单。

private List<Expense> _expenses = new List<Expense>();
public List<Expense> Items
{
    get
    {
        return this._expenses;
    }
}

我绑定到 XAML。 (我用的是分页模板)

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        this.DefaultViewModel["Items"] = _data.Items;
    }

然后我显示它

<UserControl.Resources>
    <CollectionViewSource
        x:Name="itemsViewSource"
        Source="{Binding Items, Mode=TwoWay}"/>
</UserControl.Resources>

<ListView
    x:Name="itemListView"
    AutomationProperties.AutomationId="ItemsListView"
    AutomationProperties.Name="Items"
    Margin="120,0,0,60"
    ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
    SelectionChanged="ItemListView_SelectionChanged"
    ItemTemplate="{StaticResource DefaultListItemTemplate}"/>

效果很好。然后,当用户单击按钮时,我将一个新项目添加到我的列表中

_data.Items.Add(new Expense
{
    Total = 100,
    When = new DateTime(2013, 6, 6),
    For = "Myself"
});

我期待ListView 会自动刷新,因为我设置了Mode=TwoWay,但它没有。我是否误解了这个概念并且列表无法刷新?否则,我会做错什么?

【问题讨论】:

    标签: c# data-binding microsoft-metro windows-runtime


    【解决方案1】:

    为了在您对集合进行更改后更新 UI,您需要实现 INotifyCollectionChanged。这将在发生更改时通知 UI,并通过在更改之上重新绑定 UI 来响应。

    实现这个接口是相当复杂的。相反,您应该只使用 ObservableCollection&lt;T&gt; 代替 List&lt;T&gt; 并且该场景应该可以正常工作

    private ObservableCollection<Expense> _expenses = new ObservableCollection<Expense>();
    public ObservableCollection<Expense> Items
    {
        get
        {
            return this._expenses;
        }
    }
    

    【讨论】:

    • 非常感谢。同一个主题,当对象本身发生变化时如何通知?
    • @Jonas 对象本身必须实现INotifyPropertyChanged
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    相关资源
    最近更新 更多