当我更新GridView捆绑的集合时如何更新GridView?

时间:2014-04-09 11:26:47

标签: c# wpf .net-4.5

GridView与某些集合捆绑在一起。当我从代码隐藏中删除此集合中的项目时,GridView不会更改其内容。

private void PriceRange_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
    {
        SfRangeSlider rangeSlider = sender as SfRangeSlider;
        if (rangeSlider != null)
        {
            double currentMaxValue = Math.Round(rangeSlider.Value);
            if (this.DataContext != null)
            {
                (this.DataContext as SearchViewModel).TicketModels.RemoveAll(x => (GetPriceFromTicket(x.Price) > currentMaxValue));
                var m = (this.DataContext as SearchViewModel).TicketModels.Count;
            }
        }
    }

如果我跟踪m变量,我可以看到TicketModels.Count发生变化,但我无法在UI上看到它。 顺便说一句,TicketModels有List<>类型,我应该将其更改为ObservableCollection<>吗?

1 个答案:

答案 0 :(得分:2)

绑定源的类型,即在视图模型中声明的属性在视图中绑定的数据(在您的示例中为TicketModels)应该是实现INotifyCollectionChanged的类型。 ObservableCollection<T>实现了此接口(INotifyPropertyChanged除外)。

这是有效的,因为Binding会收听INotifyCollectionChanged.CollectionChanged事件,ObservableCollection<T>会在添加或删除元素时引发该事件。

如果您需要清除收藏品,只需使用ObservableCollection<T>.Clear()

我通常将我的ObservableCollection设为只读,然后使用以下扩展方法在需要时替换内容。

/// <summary>
/// Replaces the content of a collection with the content of another collection.
/// </summary>
/// <typeparam name="TSource">The type of elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The target data collection.</param>
/// <param name="sourceCollection">The collection whose elements should be added to the System.Collections.Generic.ICollection&lt;T&gt;.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
public static void ReplaceContentWith<TSource>(this ICollection<TSource> source, IEnumerable<TSource> sourceCollection)
{
    if (source == null)
        throw new ArgumentNullException("source");

    source.Clear();
    source.AddRange(sourceCollection);
}

用法:

var foo = new ObservableCollection<string>();
var bar = new List<string> { "one", "two", "three" };
foo.ReplaceContentWith(bar);