wpf - 绑定itemsource后如何清除WPF ItemList?
问题描述
我有一个清单:
private ObservableCollection<SensorListViewItemModel> sensorList = new ObservableCollection<SensorListViewItemModel>();
我的模型是这样的:
public class SensorListViewItemModel
{
/// <summary>
/// Gets or sets the internal Id.
/// </summary>
public Guid InternalId { get; set; } = Guid.NewGuid();
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Get or sets the point.
/// </summary>
public System.Drawing.PointF PointOnImage { get; set; }
/// <summary>
/// Gets or sets the number of this sensor.
/// </summary>
public int Number { get; set; }
/// <summary>
/// Gets or sets the fill color.
/// </summary>
public Color Color { get; set; } = Colors.Black;
/// <summary>
/// Covnerter for Brush and MVVM Data Binding in the ListView
/// </summary>
public Brush ColorAsBrush
{
get
{
return new SolidColorBrush(Color);
}
}
}
现在我在我的 WPF 窗口的 WindowLoaded 事件中将它绑定到我的 ListView:
this.SensorListView.ItemsSource = this.sensorList;
现在我添加了一些工作正常的项目:
this.sensorList = new ObservableCollection<SensorListViewItemModel>();
for (int i = 1; i <= 5; i++)
{
this.sensorList.Add(new SensorListViewItemModel()
{
Number = i,
Name = "Sensor " + i,
Color = ColorHelper.FromStringAsMediaColor(this.userSettings.DataSerieColors[i - 1])
});
}
现在项目列表显示 5 个项目 - 好的。
现在我想清除 itteams:
this.sensorList.Clear();
或者
this.sensorList = new ObservableCollection<SensorListViewItemModel>();
但两者都不起作用
解决方案
的全部目的ObservableCollection
是您应该只创建一次,然后只需修改现有集合。
正如 Clemens 在评论中指出的那样,您没有进行数据绑定 - 为此您需要在 ViewModel 上使用公共属性。
所以你的 ViewModel 代码应该是这样的
public class SensorListViewModel
{
private readonly ObservableCollection<SensorListViewItemModel> _sensorList = new ObservableCollection<SensorListViewItemModel>();
public IEnumerable<SensorListViewItemModel> SensorList => _sensorList;
private void AddSensorItems(IEnumerable<SensorListViewItemModel> items, bool clearExistingItems)
{
if (clearExistingItems)
_sensorList.Clear();
foreach(var item in items)
_sensorList.Add(item);
}
请注意,您不必将 SensorList 属性声明为ObservableCollection
- 绑定会处理这一点。
然后在您的视图中,将其设置DataContext
为 SensorListViewModel 的一个实例,并将 ListView 的 ItemsSource 属性绑定到 SensorList 属性。
推荐阅读
- php - 在另一个表上显示基于外国 id 的列数据
- video - 无法将视频分割成更小的部分
- nosql - 手动恢复发电机数据库表的最佳方法是什么?
- javascript - 从javascript / node js中的map函数获取值
- nginx-reverse-proxy - 用于多种流量的 Nginx `stream`
- c++ - 成员变量作为默认参数?
- powershell - PowerShell SSH 仅适用于 LAN,但不适用于 Internet
- python - 有没有办法在亚马逊产品页面上抓取和下载视频?
- java - 如何修改JNI String的每个字符码?
- qlikview - 在 QLIK 中,如何根据表 A 中的条件将数据从表 B 添加到表 A