c# - 在 View 模型中使用mvvm消息的字符串值作为变量

标签 c# wpf mvvm mvvm-light messaging

我基于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/

相关文章:

c# - Entity Framework : StoreGeneratedPattern ="Computed" property

c# - 用于最后操作的轮换列表的集合是什么?

c# - 如何获取文本文件中同一字符串的最后两次出现 C#

c# - 为什么单击树抛出 'System.Windows.Documents.Run' 不是 Visual 或 Visual3D 的 InvalidOperationException?

WPF 动态内容选项卡不适合替代 MDI 用户界面

mvvm - 嵌套 View 模型的嵌套 View

c# - 如何为 WPF 数据网格中的特定列设置 StringFormat,其值通过 ItemsSource 方法填充

c# - Json.NET Schema 会忽略 $schema 吗?

wpf - 将 [VisualStateManager] View 状态绑定(bind)到 MVVM View 模型?

wpf - 为什么与用户控件代码隐藏中的属性的相对源绑定(bind)失败?