我基于viewModel 2中datagrid的selectionchanged过滤了viewModel 1中的listcollectionview。为此,我使用了mvvm消息传递。每次数据网格的选择更改时,都会发送一条消息来更新我的listcollectionview。这一切都很好。
现在,我需要使用此消息的字符串值来传递到过滤器中。问题是我只能在updateShotList方法中使用字符串值,而不能在 bool IsMatch中使用。如何使这项工作有效,或者如何将消息的字符串值用作 View 模型中的变量。
这就是我的 View 模型的样子。
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);
}
最佳答案
您可以将谓词创建为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;
}
关于c# - 在 View 模型中使用mvvm消息的字符串值作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31087848/