在C#中,ObservableCollection<T>
是一个动态数据集合,它提供了集合更改的通知功能。当集合中的元素被添加、移除或重新排序时,它会自动通知绑定的UI进行更新。这在构建响应式用户界面时非常有用。
ObservableCollection<T>:
System.Collections.ObjectModel
命名空间下的一个类。Collection<T>
类,并实现了 INotifyCollectionChanged
和 INotifyPropertyChanged
接口。CollectionChanged
事件。假设你有一个表示无线局域网配置文件的类 WirelessProfile
,你可以这样使用 ObservableCollection<T>
:
using System.Collections.ObjectModel;
public class WirelessProfile
{
public string Name { get; set; }
public string SSID { get; set; }
public string Password { get; set; }
}
public class NetworkManager
{
// 创建一个ObservableCollection来存储无线局域网配置文件
private ObservableCollection<WirelessProfile> _profiles = new ObservableCollection<WirelessProfile>();
// 提供一个公共属性以便外部访问
public ObservableCollection<WirelessProfile> Profiles
{
get { return _profiles; }
}
// 添加一个新的无线局域网配置文件
public void AddProfile(WirelessProfile profile)
{
_profiles.Add(profile);
}
// 移除一个无线局域网配置文件
public void RemoveProfile(WirelessProfile profile)
{
_profiles.Remove(profile);
}
}
问题: 当尝试在UI线程之外修改 ObservableCollection<T>
时,可能会抛出异常。
原因: ObservableCollection<T>
不是线程安全的,如果在非UI线程上进行修改,可能会导致竞态条件和不可预测的行为。
解决方法: 使用 Dispatcher
或 SynchronizationContext
来确保在UI线程上进行集合的修改。
// 使用Dispatcher确保在UI线程上执行
Application.Current.Dispatcher.Invoke(() =>
{
networkManager.Profiles.Add(newProfile);
});
// 或者使用SynchronizationContext
SynchronizationContext uiContext = SynchronizationContext.Current;
uiContext.Post(state =>
{
networkManager.Profiles.Add(newProfile);
}, null);
ObservableCollection<T>
是一个泛型集合,可以存储任何类型的对象。在上面的例子中,我们存储了 WirelessProfile
类型的对象。
总之,ObservableCollection<T>
是一个强大的工具,特别是在需要实时响应数据变化的WPF和UWP应用程序中。
领取专属 10元无门槛券
手把手带您无忧上云