How to Display ObservableCollection in a UserControl

后端 未结 4 1462
滥情空心
滥情空心 2021-01-15 13:48

I\'m new to WPF and I\'ve found some similar questions but can\'t quite figure out the last part. I have a ViewModel with an ObservableCollection that contains error messag

4条回答
  •  温柔的废话
    2021-01-15 14:22

    Simplest way:

    Assuming your viewmodel implements INotifyPropertyChange, create an event handler for the ObservableCollection PropertyChanged event. Create a property which aggregates all of the items in the observable colleciton into a single string. Whenever the observable collection changes, fire off a notification event for your new property. Bind to that property

    public class ViewModel : INotifyPropertyChange
    {
        public ViewModel()
        {
            MyStrings.CollectionChanged += ChangedCollection;
        }
        public ObservableCollection MyStrings{get;set;}
    
        public void ChangedCollection(args,args)
        {
            base.PropertyChanged("MyAllerts");
        }
    
        public string MyAllerts
        {
            get
            {
                string collated = "";
                foreach(var allert in MyStrings)
                {
                    collated += allert;
                        collated += "\n";
                }
            }
        }
    
    }
    

    I know this code is fraught with errors (i wrote it in SO instead of VS), but it should give you some idea.

提交回复
热议问题