PropertyChanged事件已触发,但未调用属性getter

时间:2017-05-26 16:55:36

标签: c# wpf xaml

我遇到了触发PropertyChanged事件的问题,但是UI没有更新,并且没有调用相关的属性getter。在其他SO帖子中,我发现当视图中没有任何内容实际绑定到属性时,人们会遇到此问题,但我确实有一些限制。

这是一个我试图拥有"年龄"每当在DatePicker中更改新的出生日期时输出更新。相关的代码,我尽可能地煮熟了:

型号:

public class Pft {
    public DateTime Dob;
}

视图模型:

public class ViewModelBase : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class PftViewModel : ViewModelBase {
    private Pft pft;

    public DateTime Dob {
        get { return pft.Dob; }
        set {
            pft.Dob = value;
            NotifyPropertyChanged();
            DemographicsChanged();
        }
    }

    public int Age {
        get {  // << this does not get called after NotifyPropertyChanged("Age")
            DateTime today = DateTime.Today;

            int age = today.Year - Dob.Year;

            if (Dob > today.AddYears(-age)) {
                age--;
            }

            return age;
        }
    }

    private void DemographicsChanged() {
        NotifyPropertyChanged("Age");  // << this gets called!
    }

    public PftViewModel() {
        pft = new Pft();
    }
}

public class EntryPageViewModel : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private PftViewModel _pft;
    public PftViewModel Pft {
        get { return _pft; }
        set {
            _pft = value;
            NotifyPropertyChanged();
        }
    }

    public EntryPageViewModel() {
        Pft = new PftViewModel();
    }
}

查看:

<Page x:Class="EntryPage">
    <StackPanel>
        <DatePicker SelectedDate="{Binding Pft.Dob}" />
        <TextBlock Text="{Binding Pft.Age, Mode=OneWay}" />
    </StackPanel>
</Page>

查看代码背后:

public partial class EntryPage : Page {
    private EntryPageViewModel viewModel;

    public EntryPage() {
        InitializeComponent();

        viewModel = new EntryPageViewModel();
        DataContext = viewModel;
    }
 }

0 个答案:

没有答案