use string value of mvvm message as variable in viewmodel

112 Views Asked by At

I'm filtering a listcollectionview in viewModel 1 based on selectionchanged of datagrid in viewModel 2. To do this I use mvvm messaging. Each time the selection of the datagrid changes a message is send to update my listcollectionview. This all works well.

Now I need to use the string value of this message to pass into the filter. The problem is that I can only use the string value in the updateShotList method but not into the bool IsMatch. How can I make this work, or how can I use the string value of the message as a variable in my viewmodel.

This is how my viewmodel looks like.

private ObservableCollection<Shot> _allShots = new ObservableCollection<Shot>();
public ObservableCollection<Shot> AllShots
    {
        get { return _allShots; }
        set { _allShots = value; RaisePropertyChanged();}
    }

private ListCollectionView _allShotsCollection;
public ListCollectionView AllShotsCollection
    {
        get
        {
            if (_allShotsCollection == null)
            {
                _allShotsCollection = new ListCollectionView(this.AllShots);
            }
           return _allShotsCollection;
        }
        set
        {
            _allShotsCollection = value; RaisePropertyChanged();
        }
   }

private void UpdateShotList(string SceneNr) // value sceneNr comes from message from viewmodel 2
    {
        _allShotsCollection.IsLiveFiltering = true;
        _allShotsCollection.Filter = new Predicate<object>(IsMatchFound);
    }

    bool IsMatchFound(object obj)
    {
=====>  if (obj as Shot != null && (obj as Shot).SceneNumber == "?????") // Here I need the value of string ScenNr that comes from the message.
        {
            return true;
        }
        return false;
    }

    public ShotListViewModel()
    {
        Messenger.Default.Register<string>(this, "UpdateShotList", UpdateShotList);

    }
1

There are 1 best solutions below

2
On BEST ANSWER

You can create your predicate as a lambda expression and close over SceneNr to capture it:

_allShotsCollection.Filter = o =>
{
    var shot = o as Shot;
    return shot != null && shot.SceneNumber == SceneNr;
};

Alternatively, simply introduce an instance variable to contain your filter string and update it each time you receive a message:

private string _sceneNr; 

private void UpdateShotList(string sceneNr)
{
    // ...
    _sceneNr = sceneNr;
}

bool IsMatchFound(object obj)
{
    var shot = obj as Shot;
    return shot != null && shot.SceneNumber == _sceneNr;
}