如何在绑定项目源后清除 WPF 项目列表?

How to clear WPF ItemList after binding the itemsource?

我有一个列表:

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 window 的 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 个项目 - 好的。

现在我要清除项目:

                    this.sensorList.Clear();

            this.sensorList = new ObservableCollection<SensorListViewItemModel>();

但两者都不行

ObservableCollection 的全部目的是您应该只创建一次,然后只需修改现有集合。

正如 Clemens 在评论中指出的那样,您没有进行数据绑定 - 您需要在 ViewModel 上使用 public 属性。

所以您的 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 属性。