---
title: "Properties修改模型后更新视图"
author: "winseclone"
date: "2013-02-05T11:24:45Z"
tags: []
categories: ["编程语言"]
slug: "properties"
draft: false
lastmod: "2013-02-05T14:34:45Z"
id: 1789736
url: "https://winseclone.iteye.com/blog/1789736"
---

本文是在 [http://winseclone.iteye.com/blog/1774307](/blog/1774307) 基础上，实现模型属性值改变后更新视图。

 

在Eclipse-[articles](http://www.eclipse.org/articles/Article-Properties-View/properties-view.html) 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。

![](http://dl.iteye.com/upload/attachment/0079/7081/eca0ad4a-956e-3082-b6e8-791dd95a07ab.png)

 

其次，当模型属性改变时，通过模型的eAdapters()获得监听器，通知监听者更新视图TreeViewer。  
![](http://dl.iteye.com/upload/attachment/0079/7037/c6da6de3-76cd-3f0d-a72c-e959ef840298.png)

 

通知监听器，更新视图：  
![](http://dl.iteye.com/upload/attachment/0080/3049/a3e7aa14-7519-3d61-ab3d-b74bd75d2f73.png)

 

 

++ 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://www.vogella.com/articles/EclipseEMFNotification/article.html)

[http://wiki.eclipse.org/EMF/Recipes#Notification\_Framework\_Recipes](http://wiki.eclipse.org/EMF/Recipes#Notification_Framework_Recipes)

[http://yiliner.iteye.com/blog/213846](http://yiliner.iteye.com/blog/213846) (ContentAdapter会监听孩子的变化， 添加到notifier的时刻会递归添加到其孩子）

```
resource.eAdapters().add(contentAdapter); 
```