c# - 观察者模式或数据绑定(bind)

标签 c# data-binding user-interface observer-pattern

我的问题是,您会实现观察者模式,还是使用数据绑定(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)而不是通知观察者更改,这会是一个更灵活的设计吗?我想我真正要问的是,以视觉方式表示业务对象的最灵活的方式是什么,并且不断实时更新。

alt text http://devpupil.net/GuiConcept.PNG

最佳答案

我会使用观察者。当它们表示的底层模型/数据发生变化时,GUI 会自动更新其值,这是使用观察者模式的经典示例之一。

关于c# - 观察者模式或数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1126035/

相关文章:

c# - Windows 窗体应用程序中不同线程中的 GUI 和逻辑分离

java - 重新填充 GridBagLayout 中的空单元格

python - 按下按钮时显示一组重复图像的简单图形用户界面

c# - 无法在 Visual Studio 中使用 WSDL 添加服务引用

c# - Ninject InThreadScope 绑定(bind)

javascript - JS - 将数组或字符串转换为参数列表 [SQLite insert with bind parameters]

c# - DataGridView 使用 DataSourceNullValue : enter either nothing, 或 nullValue

c# - 清除文件内容

c# - 在给定 IP 范围内的机器上远程执行 Powershell 脚本

data-binding - 服务和组件属性之间的angular2数据绑定(bind)