我通过以下方式创建了 DP:
public static readonly DependencyProperty SchoolsViewModelProperty =
DependencyProperty.Register("SchoolsViewModel", typeof(SchoolsViewModel), typeof(SchoolChooser), new PropertyMetadata(default(SchoolsViewModel)));
public SchoolsViewModel SchoolsViewModel
{
get
{
return (SchoolsViewModel)GetValue(SchoolsViewModelProperty);
}
set
{
SetValue(SchoolsViewModelProperty, value);
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
接下来,我将它绑定到 DataContext:
<common:LayoutAwarePage
...
DataContext="{Binding ElementName=SchoolChooserPage, Path=SchoolsViewModel}"/>
然后,我在 costructor 中设置属性:
public SchoolChooser()
{
this.InitializeComponent();
this.SchoolsViewModel = new SchoolsViewModel { Schools = TypeService.Resolve<ISchoolContext>().Schools };
}
不幸的是,DataContext 始终为空。在我看来,绑定不起作用。我不知道为什么,这种方式在 wpf 中起作用。
当我直接设置 DataContext 时:
this.DataContext = this.SchoolsViewModel;
一切都很好。为什么?什么,虽然我已经实现了 INotfiyProperyChanged,但事件 ProperyChanged 为空。