mvvm binding image source to dictionary item

HI!

I am a really beginner with Xamarin and MVVM, and I want to use Dictionary ítems as the Image Source of serveral images on a View.

I have several elements in a View.
I created a Dictionary<string, string>in the Viewmodel, caklled dictFotosImageSources.
Then, I tried using: Source="{Binding dictFotosImageSources[FotoFachada01]}" in 3 Images (obviously using a different Key on each one)

Well, when I try to load the View, the Apps dies.

In my ViewModel:

// Creating an Attribute
    Dictionary<string, string> _dictFotosImageSources;
// Creating the associatd Property
    public Dictionary<string, string> dictFotosImageSources
    {
        get
        {
            return _dictFotosImageSources;
        }
        set
        {
            if (_dictFotosImageSources != value)
            {
                _dictFotosImageSources = value;
                PropertyChanged?.Invoke(
                    this,
                    new PropertyChangedEventArgs(nameof(dictFotosImageSources)));
            }
        }
    }

// Within the constructor
    dictFotosImageSources = new Dictionary<string, string>();
    dictFotosImageSources.Add("FotoFachada01", "");
    dictFotosImageSources.Add("FotoFachada02", "");
    dictFotosImageSources.Add("FotoFachada03", "");

I will put valid paths to images on the Values of each KeyValue pair later, when taking a picture.

In myView
     <Image Source="{Binding dictFotosImageSources[FotoFachada01]}"></Image>

Well, the App crashes apparently when assigning the initial values in the constructor.
What am I doing wrong?

Thank you.

Answers

  • IvanositoIvanosito COMember ✭✭

    Hi!
    I found out I needed an ObservableDictionary and actually found a class which says it implements everything required to be Observable, so I added it to my PCL Project, and... (good news) App doesn't crash anymore! ... but (bad news), image never appears in the View.

    The ObservableDictionary class is here: https://gist.github.com/kzu/cfe3cb6e4fe3efea6d24

    I am using the Xamarin Plugin Media to take the picture. It gives me, among other things, the Path to the image, which I assign to the ObservableDictionary Ítem like this:

    dictFotosImageSources["FotoFachada01"] = file.Path;
    

    file.Path contains the path to the picture I've just captured.

    But, despite the ObservableDictionary item having the valid path in it, the image in the View, whose Source is the very same item, doesn't show the image.

    <Image Source="{Binding dictFotosImageSources[FotoFachada01]}"></Image> 
    

    If I use a string Property as the Source binding and assign the file.Path to it, the image appears.
    So, it's like the View is not "seeing" or reaching the ObservableDictionary Property.

    Any suggestion?

    I guess it has to do with BindingContext maybe, but whew, I'm really new to MVVM and Xamarin!

    Thanks!

Sign In or Register to comment.