2013-11-09 79 views
0

我正在尝试实现MVVM,但是当视图模型更改时,我的视图不会更新。这是我的视图模型:如何在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

您绑定的路径是nested.To使其工作,你新政类应该实现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); } 
     } 
    } 

上面的代码应该工作。

BTW: 如果你必须处理类的代码没有访问权限,则触发绑定,您将不得不重新创建每次SelectedDeal的实例时的标题值被改变。