Search code examples
c#xamarinfreshmvvm

Implement an Modal with a ObservableCollection


I'm using freshmvvm.

Modal

public class Expense : INotifyPropertyChanged
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ObservableCollection<ImageSource> Images { get; set; }//here
    public event PropertyChangedEventHandler PropertyChanged;
}

I would like to give Images properties like (name, type, source)

 public ObservableCollection<ImageSource> Images { 
   public string name { get; set; }
   public string type { get; set; }
   public ImageSource source { get; set; }
 }

Solution

  • I think I understand your problem. You want to add some "metadata" to the images. You could build a wrapper class around the ImageSource or derive a class from ImageSource (I'll show both):

    Wrapper class

    public class ImageWrapper
    {
       public string name { get; set; }
       public string type { get; set; }
       public ImageSource source { get; set; }
    }
    
    public class Expense : INotifyPropertyChanged
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ObservableCollection<ImageWrapper> Images { get; set; }//here
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    Derived class

    public class MyImageSource : ImageSource
    {
       public string name { get; set; }
       public string type { get; set; }
    }
    
    public class Expense : INotifyPropertyChanged
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ObservableCollection<MyImageSource> Images { get; set; }//here
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    In the second example, you won't need a property to hold the ImageSource, since the object itsel is an ImageSource with added properties. If that has no negative impact on your application, I would go with this. If that would need to much refactoring the first is example is also ok.