using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Windows.Forms;
// code from Bill McCarthy
// http://msmvps.com/bill/archive/2005/10/05/69012.aspx
// used with permission
namespace Csla.Windows
{
  /// 
  /// Windows Forms extender control that resolves the
  /// data refresh issue with data bound detail controls
  /// as discussed in Chapter 5.
  /// 
  [DesignerCategory("")]
  [ProvideProperty("ReadValuesOnChange", typeof(BindingSource))]
  public class BindingSourceRefresh : Component, IExtenderProvider
  {
    private Dictionary _sources = new Dictionary();
    /// 
    /// Creates an instance of the object.
    /// 
    /// Container of the control.
    public BindingSourceRefresh(IContainer container)
    {
      container.Add(this);
    }
    /// 
    /// Gets a value indicating whether the extender control
    /// can extend the specified control.
    /// 
    /// The control to be extended.
    /// 
    /// This control only extends  controls.
    /// 
    public bool CanExtend(object extendee)
    {
      if (extendee is BindingSource)
        return true;
      return false;
    }
    /// 
    /// Gets the value of the custom ReadValuesOnChange extender
    /// property added to extended controls.
    /// 
    /// Control being extended.
    public bool GetReadValuesOnChange(BindingSource source)
    {
      if (_sources.ContainsKey(source))
        return _sources[source];
      return false;
    }
    /// 
    /// Sets the value of the custom ReadValuesOnChange extender
    /// property added to extended controls.
    /// 
    /// Control being extended.
    /// New value of property.
    /// 
    public void SetReadValuesOnChange(
      BindingSource source, bool value)
    {
      if (_sources.ContainsKey(source))
        _sources[source] = value;
      else
        _sources.Add(source, value);
      if (value)
      {
        // hook
        source.BindingComplete += 
          new BindingCompleteEventHandler(Source_BindingComplete);
      }
      else
      {
        // unhook
        source.BindingComplete -= 
          new BindingCompleteEventHandler(Source_BindingComplete);
      }
    }
    private void Source_BindingComplete(
      object sender, BindingCompleteEventArgs e)
    {
      e.Binding.ReadValue();
    }
  }
}