我在一个连接到视图的Presenter中有一个对象。在我的XAMTL中,我有以下内容:
<Label Content="{Binding ElementName=PSV, Path=Presenter.Portfolio.Name}"/>
现在当控件被创建时,Portfolio是null,然后我运行另一个方法来设置Portfolio。我已经实现了INotifyPropertyChanged,但到目前为止,我还没有能够触发绑定。有人可以给我一些提示吗?我可以绑定到属性的属性吗?
我在一个连接到视图的Presenter中有一个对象。在我的XAMTL中,我有以下内容:
<Label Content="{Binding ElementName=PSV, Path=Presenter.Portfolio.Name}"/>
绑定始终使用DataContext,您需要将Presenter设置为本地的DataContext。例如,您可以在Window或UserControl的构造函数中执行此操作:
this.DataContext = new Presenter();
您的绑定将会更改为:
<Label Content="{Binding ElementName=PSV, Path=Portfolio.Name}"/>
您以前路径中的Presenter部分在DataContext中是隐含的。
这样,DataContext会监视NotifyChanged事件,并在Portfolio从null更改为具有值时正确更新视图。
回答您问题的最后一部分,绑定到属性的属性确实可行。
如果您已经正确实现了INotifyPropertyChanged
,那么这将完美地工作。一些尝试的方法:
INotifyPropertyChanged
并在设置Name
时引发事件。如果所有尝试都失败了,请发布您的代码。
既然你已经实现了INotifyPropertyChanged,那么你是否确保在Portfolio.Name的setter中触发了PropertyChanged事件呢?
string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
// Alert the databinding engine about changes to the source value
OnPropertyChanged("Name");
}
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(propertyName);
}
#region INotifyPropertyChanged members
public event PropertyChangedEventHandler PropertyChanged;
#endregion