0

我正在尝试实现 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 更改时,视图不会。我错过了什么?

4

1 回答 1

1

您的绑定路径是嵌套的。要使其工作,您的Deal类也应该实现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 类的代码,那么要触发绑定,您必须在每次Title的值更改时重新创建SelectedDeal的实例。

于 2013-11-09T15:12:06.057 回答