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<>
吗?
绑定源的类型,即在视图中数据绑定的视图模型中声明的属性(在您的示例中为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<T>.</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);