【问题标题】:Problems implementing observable collection实现可观察集合的问题
【发布时间】:2012-04-17 21:30:49
【问题描述】:

我有一个存储在数据库中的对象,我在我的视图模型中检索该对象并将其放入可观察的集合中。这些对象是属性(房屋/不动产),每个都有一个称为图像的子对象。每个属性可以有多个图像(但每个图像只能有一个属性)。我只想使用一个视图模型。我的属性可以很好地填充列表框,并且可以成功地将图像绑定到后续列表框,但前提是我通过 iList 进行绑定。我的问题是如何将图像实现为它们自己的可观察集合(以便我可以监视更改),而不是 iList。这是我上面提到的一些功能的代码...

        public IList<Image> Images
    {
        get
        {
            if (CurrentProperty != null)
                return CurrentProperty.Images.ToList();
            return null;
        }
    }

 private void Load()
    {
        PropertyList = new ObservableCollection<Property>(from property in entities.Properties.Include("Images") select property);        

        //Sort the list (based on previous session stored in database)
        var sortList = PropertyList.OrderBy(x => x.Sort).ToList();
        PropertyList.Clear();
        sortList.ForEach(PropertyList.Add);

        propertyView = CollectionViewSource.GetDefaultView(PropertyList);         
        if (propertyView != null) propertyView.CurrentChanged += new System.EventHandler(propertyView_CurrentChanged);           


        public const string PropertiesPropertyName = "PropertyList";
    private ObservableCollection<Property> _PropertyList = null;

    public ObservableCollection<Property> PropertyList
    {
        get
        {
            return _PropertyList;
        }

        set
        {
            if (_PropertyList == value)
            {
                return;
            }

            var oldValue = _PropertyList;
            _PropertyList = value;

            // Update bindings, no broadcast
            RaisePropertyChanged(PropertiesPropertyName);
        }
    }    

【问题讨论】:

  • 如何更新图像?为什么只是“一个视图模型”?
  • 我更新了包含属性的 observablecollection:CurrentProperty.Images.Add(NewImage),然后将集合保存到数据库中。该程序实际上不需要 mvvm,使用它的唯一原因是利用 observablecollections 对列表框进行排序和重新排序。我确信这可以在一个视图模型中完成,如果我实际上没有充分利用 mvvm,这似乎是不必要的工作。话虽如此,如果它不会比任何其他解决方案带来更多的工作,我会认真考虑它。

标签: c# wpf binding mvvm observablecollection


【解决方案1】:

按照这个问题提供的答案最终解决了这个问题:

Listview to display ObservableSelection

我为图像创建了一个 observablecollection,然后创建了一个新方法 images_Update() ,每次视图的当前项(属性 observable 集合)更改时都会调用该方法。我还将它放在 AddImage() 和 DeleteImage() 方法的底部,以确保在调用它们时更新列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 2017-01-20
    • 2019-02-23
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多