我们知道在使用ObservableCollection作为LongListSelector的ItemsSource时,当源集合发生新增或删除元素时,会即时通知到UI作出更新。
但是当只是修改源集合里元素的属性值时,却不会通知UI更新。
为了使属性变化能够通知UI,需要为源集合的元素类实现INotifyPropertyChanged接口。
首先我们抽象一个实现INotifyPropertyChanged接口的基类BindableBase:
/// <summary> /// Implementation of <see cref="INotifyPropertyChanged"/> to simplify models. /// </summary> [Windows.Foundation.Metadata.WebHostHidden] public abstract class BindableBase : INotifyPropertyChanged { /// <summary> /// Multicast event for property change notifications. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Checks if a property already matches a desired value. Sets the property and /// notifies listeners only when necessary. /// </summary> /// <typeparam name="T">Type of the property.</typeparam> /// <param name="storage">Reference to a property with both getter and setter.</param> /// <param name="value">Desired value for the property.</param> /// <param name="propertyName">Name of the property used to notify listeners. </param> /// <returns>True if the value was changed, false if the existing value matched the /// desired value.</returns> protected bool SetProperty<T>(ref T storage, T value, String propertyName) { if (object.Equals(storage, value)) return false; storage = value; if(null != PropertyChanged) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); return true; } }
public class StockItem : BindableBase { string _stockName = string.Empty; string _stockCode = string.Empty; string _latest = string.Empty; float _zf = 0.0f; int _displayType = 0; public string StockName { get { return _stockName; } set { if (null != value) this.SetProperty(ref _stockName, value, "StockName"); } } public string StockCode { get { return _stockCode; } set { if (null != value) this.SetProperty(ref _stockCode, value, "StockCode"); } } public string Latest { get { return _latest; } set { if (null != value) this.SetProperty(ref _latest, value, "Latest"); } } public float Zf { get { return _zf; } set { this.SetProperty(ref _zf, value, "Zf"); } } //0 - 普通, 1 - 分时, 2 - K线 public int DisplayType { get { return _displayType; } set { this.SetProperty(ref _displayType, value, "DisplayType"); } } public string Percent { get { if (Math.Abs(Zf) < 0.0001f) return "0.00%"; else { if (Zf > 0.00f) return "+" + Zf.ToString() + "%"; else return "-" + Zf.ToString() + "%"; } } } public string PercentColor { get { if (Math.Abs(Zf) < 0.0001f) return "Gray"; else { if (Zf > 0.00f) return "Red"; else return "Green"; } } } }
最后,使用ObservableCollection作为该元素集合赋给LongListSelector的ItemsSource,那么在修改元素属性时就能通知更新UI了。