使用mvvm消息的字符串值作为viewmodel中的变量

时间:2015-06-27 10:44:01

标签: c# wpf mvvm mvvm-light messaging

我根据viewModel 2中datagrid的selectionchanged过滤了viewModel 1中的listcollectionview。为此,我使用了mvvm messaging。每次选择datagrid时,都会发送一条消息来更新我的listcollectionview。这一切都运作良好。

现在我需要使用此消息的字符串值传递到过滤器。问题是我只能在updateShotList方法中使用字符串值,而不能在bool IsMatch中使用。如何使这项工作,或如何在视图模型中将消息的字符串值用作变量。

这就是我的viewmodel的样子。

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 个答案:

答案 0 :(得分:0)

您可以将谓词创建为lambda表达式并关闭SceneNr以捕获它:

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

或者,只需引入一个实例变量来包含您的过滤字符串,并在每次收到消息时更新它:

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