首页 > 解决方案 > 绑定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>();

但两者都不起作用

标签: wpflistview

解决方案


的全部目的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 属性。


推荐阅读