如何在MVVM中更改视图模型时更新视图?

时间:2013-11-09 11:50:52

标签: c# mvvm binding windows-store-apps

我正在尝试实现MVVM,但是当视图模型更改时我的视图不会更新。这是我的观点模型:

public class ViewModelDealDetails : INotifyPropertyChanged
{
    private Deal selectedDeal;

    public Deal SelectedDeal
    {
        get { return selectedDeal; }
        set
        {
            selectedDeal = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

在我的XAML视图中我有这个:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
       <StackPanel>
           <TextBlock Text="{Binding Path=SelectedDeal.Title, Mode=TwoWay}"></TextBlock>
       </StackPanel>
</Grid>

交易类:

public class Deal
{
    private string title;
    private float price;

    public Deal()
    {
        this.title = "Example";    
    }

    public Deal(string title, float price)
    {
        this.title = title;
        this.price = price;
    }

    public string Title
    {
        get { return title; }
        set { title = value; }
    }

    public float Price
    {
        get { return price; }
        set { price = value; }
    }
}

当应用程序启动时,值正确,但当SelectedDeal更改时,视图不会。我错过了什么?

1 个答案:

答案 0 :(得分:1)

绑定的路径是嵌套的。要使其正常工作,您的交易类也应实施 INotifyPropertyChanged 。否则,除非更改 SelectedDeal ,否则不会触发它。我建议你制作所有继承自 BindableBase 的视图模型。它会让你的生活更轻松。

   public class ViewModelDealDetails: BindableBase
    {
        private Deal selectedDeal;

        public Deal SelectedDeal
        {
            get { return selectedDeal; }
            set { SetProperty(ref selectedDeal, value); }
        }

    }

    public class Deal: BindableBase
    {
        private string title;

        public string Title
        {
            get { return title; }
            set { SetProperty(ref title, value); }
        }
    }

以上代码应该有效。

顺便说一句: 如果您无法访问Deal类的代码,那么要触发绑定,每次更改标题的值时,您都必须重新创建 SelectedDeal 的实例。