【问题标题】:Silverlight 5 MVVM: how to trigger event from Child ViewModel to parent ViewModel? (UserControls)Silverlight 5 MVVM:如何触发从子视图模型到父视图模型的事件? (用户控制)
【发布时间】:2012-11-02 21:24:09
【问题描述】:

情况:

我有一个 UserControl(称为 UCA),它的 DataContext 绑定到一个 ViewModel(称为 VMA)。 UserControl (UCA) 有另一个 UserControl(称为 UCB)嵌套在其中,我有一个用于 UCB 的 ViewModel,称为 VMB。

父 ViewModel (VMA) 有一个属性来实例化 VMB,并将 UCB 的 DataContext 设置为 VMB。

当绑定到 VMB 的 UCB 中的控件值 (TextBox) 发生更改时,它会收到通知 (OnPropertyChanged)。现在,我需要在 VMB 中进行更改以通知“父”VMA,以便父 VMA 可以做一些工作并更新 UCA 中的控件。

所以我在 ViewModel 方面,在我的 VMB OnPropertyChanged 方法中,我试图弄清楚如何将这些数据更改冒泡到 VMA。有什么建议么?提示?

谢谢,罗伯。

【问题讨论】:

    标签: silverlight mvvm


    【解决方案1】:

    VMA 是否拥有 VMB?在 VMA 中注册事件

    public VMA()            
    {
        VMB.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(PropertyChanged);
    }
    
    void PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "MyProperty")
        {
            //TODO: Stuff
        }
    }
    

    如果 VMB 实现 INotifyProeprtyChanged,这将起作用。

    【讨论】:

    • “拥有”我假设您的意思是 VMB 是 VMA 中的定义属性?如果是这样,那么是的,VMA 拥有 VMB。 VMA 和 VMB 都实现了 INotifyPropertyChanged。我尝试了您的建议,但不断收到此语法错误(我使用的是 VB,但将您的 C# 翻译为 VB)。方法“Public Sub OnPropertyChanged(e As System.ComponentModel.PropertyChangedEventArgs)”没有与委托“Delegate Sub PropertyChangedEventHandler(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs)”兼容的签名。
    • 搞定了,非常感谢!!我正在使用 VB,所以我在翻译时有点迷失,但现在一切都好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多