0

我通过以下方式创建了 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 为空。

4

1 回答 1

0

你不需要INotifyPropertyChangedDependencyPropertys。也许删除它会让您更好地了解问题。

我想知道为什么您的视图具有视图模型的属性。视图模型不应该进入 DataContext 吗?我希望您的 View 和 ViewModel 独立于另一个实例,例如Application创建两个对象并通过将 Views 设置DataContext为 ViewModel 实例来连接它们。

例子:

var view = new View();
var viewModel = new ViewModel();

view.DataContext = viewModel;

view.Show();
于 2013-05-03T07:41:05.100 回答