本文是在 http://winseclone.iteye.com/blog/1774307 基础上,实现模型属性值改变后更新视图。
在Eclipse-articles propertyviewsample.zip的例子中adaptableObject是一个View(ButtonElement封装了Button),模型属性值改变后会通过ButtonElementProperties.firePropertyChanged(String, Object)更新Button(视图)。
protected void firePropertyChanged(String propName, Object value) {
Button ctl = element.getControl();
if (ctl == null) {
// the GUIView is probably hidden in this case
return;
}
if (propName.equals(PROPERTY_FONT)) {
ctl.setFont(new Font (ctl.getDisplay(),new FontData((String)value)) );
return;
}
if (propName.equals(PROPERTY_TEXT)) {
ctl.setText((String)value);
return;
}
}
上例中的方式,会导致代码臃肿,且灵活性不高。
EMF采用观察者模式(listener)方式来提高代码的灵活性。EMF使用到org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider类来实现。
首先,通过eAdapters()注册到模型对象 [r1] 。AdapterFactoryContentProvider中包括了Viewer视图实例,同时实现了INotifyChangedListener。
其次,当模型属性改变时,通过模型的eAdapters()获得监听器,通知监听者更新视图TreeViewer。
通知监听器,更新视图:
++ ItemPropertySource适配了Properties视图需要的IPropertySource对象
org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider.getPropertySource(Object)
|-org.eclipse.emf.edit.ui.provider.PropertySource.PropertySource(Object, IItemPropertySource)
参考:
r1:EMF监听实现:
http://www.vogella.com/articles/EclipseEMFNotification/article.html
http://wiki.eclipse.org/EMF/Recipes#Notification_Framework_Recipes
http://yiliner.iteye.com/blog/213846 (ContentAdapter会监听孩子的变化, 添加到notifier的时刻会递归添加到其孩子)
resource.eAdapters().add(contentAdapter);