[英]How to update GridView when I update a collection that GridView is binded with?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.