0

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?

4

1 回答 1

2

这个逻辑应该在 ViewModel 中。所有与视图相关的逻辑或事物的显示方式都应该在 ViewModel 中。视图 (.xaml.cs) 中不应包含任何逻辑。

您通常使用该INotifyPropertyChanged界面来通知视图发生了某些变化。在这种情况下,您希望在门状态更改时更改门图像。在这种情况下,我会尝试这样的事情。

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;
};

注意:我已将字段封装到属性中。

如果您的图像嵌入在您的组件中,请查看此链接以了解如何为您的图像编写 uri。

于 2013-04-06T09:45:41.547 回答