我的问题是,您会实现观察者模式,还是使用数据绑定(bind)来执行以下操作:
目前,我正在初始化 GuiDataObj 列表。当事件被触发时,我查找 GuiDataObjById,然后修改该对象,该对象与 GuiElement 进行数据绑定(bind);更新 GUI。
有几个 GuiElement(目前都是相同类型,但这将来可能会改变),我希望能够修改类对象,并让 GuiElement 自动神奇地更新 GuiElement反射(reflect)的变化。
public class GuiElement : ObservableImpl
{
private string guiElementName;
public String GuiElementName
{
get { return guiElementName; }
set
{
guiElementName = value;
NotifyObservers(guiElementName);
}
}
private string status;
public String Status
{
get { return status; }
set
{
status = value;
NotifyObservers(status);
}
}
}
public interface IObserver
{
void Notify<T>(T watchObj);
}
public interface IObservable
{
void Register(IObserver observer);
void UnRegister(IObserver observer);
}
public class ObservableImpl : IObservable
{
protected Hashtable _observerContainer = new Hashtable();
public void Register(IObserver anObserver)
{
_observerContainer.Add(anObserver, anObserver);
}
public void UnRegister(IObserver anObserver)
{
_observerContainer.Remove(anObserver);
}
public void NotifyObservers<T>(T anObject)
{
foreach (IObserver anObserver in _observerContainer.Keys)
anObserver.Notify(anObject);
}
}
然后让我的 GuiElement 在收到更改通知时更新 Gui?
public partial class GuiElementControl : UserControl, IObserver
{
public GuiElementControl()
{
InitializeComponent();
}
#region Implementation of IObserver
public void Notify<T>(T watchObj)
{
if (watchObj is GuiElement)
{
UpdateGui(watchObj);
}
}
private static void UpdateGui(object obj)
{
GuiElement element = obj as GuiElement;
if (element != null)
{
NameLbl.Text = element.GuiElementName;
StatusLbl.Text = element.Status;
}
}
#endregion
如果我实现数据绑定(bind)而不是通知观察者更改,这会是一个更灵活的设计吗?我想我真正要问的是,以视觉方式表示业务对象的最灵活的方式是什么,并且不断实时更新。
最佳答案
我会使用观察者。当它们表示的底层模型/数据发生变化时,GUI 会自动更新其值,这是使用观察者模式的经典示例之一。
关于c# - 观察者模式或数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1126035/