【问题标题】:WPF - Raise Event from UserControl ViewModelWPF - 从 UserControl ViewModel 引发事件
【发布时间】:2015-08-24 15:16:40
【问题描述】:

我有一个使用 MVVM 的 WPF 应用程序

MainWindowViewModel 引用了其他 ViewModel,如下所示:-

            this.SearchJobVM = new SearchJobViewModel();
            this.JobDetailsVM = new JobDetailsViewModel();
            this.JobEditVM = new JobEditViewModel();

我在 MainWindow 上有一个名为 StatusMessage 的标签,它绑定到 MainWindowViewModel 上的字符串属性

我想更新以在任何其他视图模型上更改此消息并在 UI 上更新它

我是否需要从其他 ViewModel 向 MainWindowViewModel 引发事件?

我该如何实现这一目标?

【问题讨论】:

  • 你能提供更多细节吗?您是否尝试从其他视图模型更新此 StatusMessage?或者您想在 MainViewModel 上的此 StatusMessage 更改时更新其他视图模型?

标签: c# wpf


【解决方案1】:

我认为这取决于您希望视图模型彼此独立的程度;

user3690202 的解决方案虽然可行,但确实会在 MainViewModel 上创建子视图模型(SearchJobViewModel 等)的依赖关系。

由于您的视图模型可能已经实现了 INotifyPropertyChanged,您可以将子视图模型上的消息公开为一个属性,并使 MainViewModel 监听子视图模型上的更改。

因此,您会得到如下内容:

class SearchJobViewModel : INotifyPropertyChanged
{
    string theMessageFromSearchJob;
    public string TheMessageFromSearchJob
    {
        get { return theMessageFromSearchJob; }
        set {
            theMessageFromSearchJob = value;           
            /* raise propertychanged here */ }
    }
}

然后在 MainViewModel 中:

this.SearchJobVM = new SearchJobViewModel();
this.SearchJobVM +=  SearchJobVM_PropertyChanged;

void SearchJobVM_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName == "TheMessageFromSearchJob")
    { 
        this.StatusMessage = this.SearchJobVM.TheMessageFromSearchJob;
    }
}

【讨论】:

  • 这也是一个有效的观点,我在写答案之前确实考虑过。与往常一样,这是分离和复杂性之间的微妙平衡。我的答案是简单的方法。如果你在虚拟机之间有一些概念上的分离,那么这样做,或者甚至更好地使用一个简单的事件发布/订阅模式来打破依赖是要走的路。
【解决方案2】:

我能想到的最简洁的方法(有时我自己也这样做)是将 MainWindowViewModel 的引用传递给这些子视图模型,即:

        this.SearchJobVM = new SearchJobViewModel(this);
        this.JobDetailsVM = new JobDetailsViewModel(this);
        this.JobEditVM = new JobEditViewModel(this);

然后从这些子视图模型之一中,如果您已将引用存储在名为 MainViewModel 的属性中,您可以执行以下操作:

MainViewModel.StatusMessage = "New status";

如果您的虚拟机支持 INotifyPropertyChanged,那么一切都会自动更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2010-09-16
    • 2018-03-30
    • 1970-01-01
    相关资源
    最近更新 更多