Michael Fyffe
Michael Fyffe

Reputation: 1

Dynamic VIew? where to put logic?

I am currently programming using the MVVM pattern.

My view Model Looks like so

class DoorsViewModel
{
ObservableCollection<Door> doorCollection;
};

the door class looks like the following

class Door
{
string name;
bool isOpen;
};

my view is linked to the viewmodel, and simply contains a longlistselector with a picture and the name of the door. I want the picture to be dynamic and change depending on the state of the door( whether it's open or closed ). How would i implement it so that the picture updates dynamically depending on the state of the door? should this be done in the viewmodel? or should it be done within the view?

Upvotes: 0

Views: 66

Answers (1)

vidstige
vidstige

Reputation: 13079

This logic should be in the ViewModel. All logic that is related to the view or how things are displayed should be in the ViewModel. No logic should be in the view (.xaml.cs).

You typically use the INotifyPropertyChanged interface to notify the View that something has changed. In this case you want a door image to be changed when the state of the door changes. In this case I would try something like this.

class Door: INotifyPropertyChanged
{
    private string _name;
    private bool _isOpen;

    public Uri DoorImage
    {
        get
        {
            if (_isOpen) return new Uri("uri_to_open.png");
            return new Uri("uri_to_closed.png");
        }
    }

    public bool IsOpen
    {
        get { return _isOpen; }
        set
        {
            _isOpen = value;
            RaisePropertyChanged("IsOpen");
            // important, notifies the UI to update the door image
            RaisePropertyChanged("DoorImage");
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var tmp = PropertyChanged;
        if (tmp != null) tmp(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
};

Note: I have encapsulated the fields into properties.

If your image is embedded in your assebmly, please check out this link to learn how to write an uri for your image.

Upvotes: 2

Related Questions